模板字符串
${}中可以嵌入變量和表達式
var a = 1;
var b = 2;
var str = `
<ul>
<li>${a}</li>
<li>$</li>
</ul>`
字符串的解析構(gòu)值
var [c,p] = "呵呵";
console.log(c + "+" + p); // 呵+呵
字符串方法的擴展
includes(string,index):
includes(string,index)判斷一個字符串中是否包含了某個字符串,index參數(shù)代表的是從哪里開始搜索,,注意index是從0開始的。
var str = "ZI符串";
console.log(str.includes("ZI")); //true
console.log(str.includes("ZI",1)); //false
startsWith(string,index):
startsWith(string,index)判斷一個字符串是否頭部包含了某個字符串,index表示從哪里開始計算,注意index是從0開始的。
var str = "ZI符串";
console.log(str.startsWith("I")); //false
console.log(str.startsWith("I",1)); //true
endsWith(string,index):
endsWith(string,index)判斷一個字符串是否在尾部包含了某個字符串,index表示從哪里開始計算,注意index是從0開始的。
var str = "ZI符串";
console.log(str.endsWith("串")); //true
console.log(str.endsWith("串",1)); //false
console.log(str.endsWith("Z",1)); //true
console.log(str.endsWith("Z",0)); //false
console.log(str.endsWith("Z",2)); //false
repeat(number):
repeat(number)將字符串復(fù)制N次注意的是0次就消失了1次不會產(chǎn)生變化,得到的是一個新的字符串要用一個變量去接收。
var str = "ZI符串";
var new = str.repeat(2); // ZI符串ZI符串
codePointAt(index):
codePointAt(index) 字符串方法,傳入的是字符串的index返回值為當(dāng)前下標(biāo)字符所對應(yīng)的編碼值,注意的是雖然ES6比ES5有所提升但是仍然有所缺陷。
var str = "NSString";
var num =str.codePointAt(0);
console.log(num); //83
var str = "字符串";
var num =str.codePointAt(2);
console.log(num); // 20018
fromCharCode(code):
fromCharCode(code)與codePointAt(index)正好相反根據(jù)編碼返回字符串
var str = String.fromCodePoint(20018);
console.log(str); // 串
normalize():
normalize()語調(diào)符號和重音符號的統(tǒng)一,Unicode正規(guī)化()中有4個參數(shù)來選擇NFC默認(rèn)的,返回多個簡單字符的合成字符。NFD即在標(biāo)準(zhǔn)等價的前提下,返回合成字符分解的多個簡單字符。NFKC返回合成字符。NFKD返回合成字符分解的多個簡單字符。
str.normalize('NFC'); // 需求中沒遇到過
字符串與新的遍歷方式
for(let x of string){}可以將字符串每個都取出放到名叫x的常量中來進行循環(huán)
var str = "ZI符串";
for(let index of str){
console.log(index); // 打印 Z I 符 串
}
Iterator接口,每個字符串中都有一個Symbol.iterator函數(shù),調(diào)用后可以返回一個Iterator對象,這個對象有一個next方法,其方法是通過指針的偏移達到遍歷內(nèi)存中的所有字符。
var str = "ABCDEFG";
var Iterator = str[Symbol.iterator();
console.log(Iterator.next()) // Object {value: "A", done: false}
console.log(Iterator.next()) // Object {value: "B", done: false}
console.log(Iterator.next()) // Object {value: "C", done: false}
console.log(Iterator.next()) // Object {value: "D", done: false}
console.log(Iterator.next()) // Object {value: "E", done: false}
console.log(Iterator.next()) // Object {value: "F", done: false}
console.log(Iterator.next()) // Object {value: "G", done: false}
console.log(Iterator.next()) // Object {value: undefined, done: true}
console.log(Iterator.next()) // Object {value: undefined, done: true}
貌似暫時并未實行
at(index)
at(index)根據(jù)下表取出對應(yīng)的字符
var str = "ZI符串";
for(let i = 0;i<str.length;i++){
if(str.at(i) === "I"){
console.log("有I");
}
}
padStart(number,string)
padStart(number,string)根據(jù)number來計算字符串的長度如果不夠會在后面進行補位
var str = "100";
str.padStart(6,"00");
padEnd(number,string)
padEnd(number,string)根據(jù)number來計算字符串的長度如果不夠會在前面進行補位
var str = "100";
str.padEnd(6,"00");