es6基礎系列四--字符串的拓展

1 for...of 字符串的遍歷接口

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

2 includes 是否包含某字符串,返回布爾值

格式:str.includes(searchString[, position])
與indexOf的對比:
indexOf:返回下標,判斷是否包含某字符串,下標是字符串的位置
includes:返回布爾值,是否包含某字符串,若是隻是判斷字符串中包含,此法可行。
es6

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])this

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

// 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官網spa

相關文章
相關標籤/搜索