Javascript6中字符串的四个新用法分享

以下就是JavaScript6中字符串的四个新用法:

一、Unicode字符的新表示方法

Unicode字符通常是21个bit的,而普通的JavaScript字符(大部分)是16bit的,可以编码成UTF-16。超过16bit的字符需要用2个常规字符表示。

比如,下面的的代码将会输出一个Unicode小火箭字符(‘\uD83D\uDE80'),你可以在浏览器的console里试一下:

console.log('\uD83D\uDE80');

在 ECMAScript 6 里,可以使用新的表示方法,更简洁:

console.log('\u{1F680}');

二、多行字符串定义和模板字符串

模板字符串提供了三个有用的语法功能。

首先,模板字符串支持嵌入字符串变量:

let first = 'Jane'; let last = 'Doe'; console.log(`Hello ${first} ${last}!`); // Hello Jane Doe!

第二,模板字符串支持直接定义多行字符串:

let multiLine = ` This is a string with multiple lines`;

第三,如果你把字符串加上String.raw前缀,字符串将会保持原始状况。反斜线(\)将不表示转义,其它专业字符,比如 \n 也不会被转义:

let raw = String.raw`Not a newline: \n`; console.log(raw === 'Not a newline: \\n'); // true

三、循环遍历字符串

字符串可遍历循环,你可以使用 for-of 循环字符串里的每个字符:

for (let ch of 'abc') { console.log(ch); } // Output: // a // b // c

而且,你可以使用拆分符 (...) 将字符串拆分成字符数组:

let chars = [...'abc']; // ['a', 'b', 'c']

四、字符串包含判断和重复复制字符串

有三个新的方法能检查一个字符串是否包含另外一个字符串:

> 'hello'.startsWith('hell') true > 'hello'.endsWith('ello') true > 'hello'.includes('ell') true

这些方法有一个可选的第二个参数,指出搜索的起始位置:

> 'hello'.startsWith('ello', 1) true > 'hello'.endsWith('hell', 4) true > 'hello'.includes('ell', 1) true > 'hello'.includes('ell', 2) false

repeat()方法能重复复制字符串:

> 'doo '.repeat(3) 'doo doo doo '

总结

以上就是关于Javascript6中字符串的四个新用法,大家都学会了吗?希望这篇文章对大家能有所帮助,如果有疑问大家可以留言交流。

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzjpxf.html