首頁  >  文章  >  web前端  >  es6的基礎介紹--字串的拓展

es6的基礎介紹--字串的拓展

零下一度
零下一度原創
2017-05-16 10:04:171364瀏覽

1 for...of 字串的遍歷介面

for(let i of "abc"){
    console.log(i);
}
// a
// b
// c

2 includes 是否包含某個字串,傳回布林值

格式:str.includes(searchString[, position])
與indexOf的比較:
indexOf:傳回下標,判斷是否包含某字串,下標是字串的位置
includes :傳回布林值,是否包含某字串,如果只是判斷字串中包含,此法可行。

var s = "hello";
// es5
s.indexOf("o"); // 4
// es6
s.includes("o"); // true
s.includes("d"); // false
s.includes("h", 2); // false 从第三个字符开始找

3 startsWith 參數字串是否在來源字串的頭部,傳回布林值

格式:str.startsWith(searchString[, position])

var s = "hello world";
// es5
s.indexOf("hello"); // 0 等于0表示就在源字符串头部
// es6
s.startsWith("hello"); // true
s.startsWith("world"); // false
s.startsWith("world", 6); // true

4 endsWith 跟startsWith相反,表示參數字串是否在來源字串的尾部,回傳布林值

格式:str.endsWith(searchString[, position])

var s = "hello world";
// es5
String.prototype.endWith=function(endStr){
  var d=this.length-endStr.length;
  return (d>=0&&this.lastIndexOf(endStr)==d)
}
s.endWith("world"); // true
// es6
s.endsWith("world"); // true
s.endsWith("world", 5); // false
s.endsWith("hello", 5); // true

5 repeat將原始字串重複n次,傳回一個新字串

var s = "s";
s.repeat(3); // sss
s.repeat(2.6); // ss 小数会被取整
s.repeat(-2); // RangeError 报错
s.repeat(0); // ""

6 模板字串是增強版的字串,用反引號(`)標識。

它可以當作普通字串使用,也可以用來定義多行字串,或是在字串中嵌入變數,好處相當明顯,不用再拼接字串,使用模板字串內部可以使用變數了。

// es5 输出模板通常是如下格式,相当繁琐还不方便
var name="Bob",time="today";
var resultStr = "hello "+name+", how are you "+time+'?'; //hello Bob, how are you today?
// es6 模板字符串
console.log(`string text line 1
string text line 2`);
//string text line 1
//string text line 2

// 直接用${变量名}表示
`Hello ${name}, how are you ${time}?` // Hello Bob, how are you today?
// 使用表达式
var obj={a:1,b:2};
`${obj.a+obj.b}` // 3
// 使用函数
function fn() {
  return "Hello World";
}
`this is fn return str: ${fn()}` // this is fn return str: Hello World

具體es6關於字串的變更、拓展請查看MDN官網

【相關推薦】

1. 特別推薦「php程式設計師工具箱」V0.1版本下載

2. 免費js線上影片教學

3. php.cn獨孤九賤(3)-JavaScript影片教學##

以上是es6的基礎介紹--字串的拓展的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn