ES6----->字符串

86 阅读1分钟

字符的 Unicode 表示法

采用\uxxxx形式表示一个字符,其中xxxx表示字符的 Unicode 码点。

let str="\uD842\uDFB7";
let str="\u{20BB7}"; //{}不管双字节和单字节都可以使用
console.log(str);

const str2=`sdhiowhgo`;//中间可以填写字符串
console.log(str2);

let str2 = String.raw`hi ${str}`; //  \n后面的原样输出
console.log(str2);

字符串的遍历器接口

字符串可以被for...of循环遍历。

for (const item of str) {
    console.log(item);
}

这个遍历器最大的优点是可以识别大于0xFFFF的码点,传统的for循环无法识别这样的码点

let str="\u{20BB7}"; //{}不管双字节和单字节都可以使用
for (let i = 0; i < str.length; i++) {
    console.log(str[i]);
}
for (const item of str) {
    console.log(item);
}

实例方法

  • includes() :返回布尔值,表示是否找到了参数字符串。
  • startsWith() :返回布尔值,表示参数字符串是否在原字符串的头部。
  • endsWith() :返回布尔值,表示参数字符串是否在原字符串的尾部。
let s = 'Hello world!';

s.startsWith('Hello') // true
s.endsWith('!') // true
s.includes('o') // true


let s = 'Hello world!';

s.startsWith('world', 6) // true
s.endsWith('Hello', 5) // true
s.includes('Hello', 6) // false