ES6实战——字符串
在 ES6 中,标准库升级了很多,在这些变化中有许多新的对于字符串的函数,比如 .includes() 和 .repeat()。
.includes( )
1 2 3 4 | var string = 'food' ; var substring = 'foo' ; console.log(string.indexOf(substring) > - 1 ); / / true |
之前我们使用 indexOf() 函数的返回值是否 >-1 来判断字符串是否包含某些字符串,现在我们更简单地使用 .includes() 来返回一个布尔值来判断:
1 2 3 4 | const string = 'food' ; const substring = 'foo' ; console.log(string.includes(substring)); / / true |
.repeat( )
1 2 3 4 5 6 7 | function repeat(string, count) { var strings = []; while (strings.length < count) { strings.push(string); } return strings.join(''); } |
在 ES6 中,可以更简便地实现:
1 | 'meow' .repeat( 3 ); / / 'meowmeowmeow' |
模版字符串
使用 模版字符串 我们就可以不用对某些特殊字符进行转义处理了:
1 | var text = "This string contains \"double quotes\" which are escaped." ; |
1 | let text = `This string contains "double quotes" which don't need to be escaped anymore.`; |
模版字符串 还支持插入,可以把变量值和字符串连接起来.
1 2 3 4 | var name = 'Tiger' ; var age = 13 ; console.log( 'My cat is named ' + name + ' and is ' + age + ' years old.' ); |
还可以更简单:
1 2 3 4 | const name = 'Tiger' ; const age = 13 ; console.log(`My cat is named ${name} and is ${age} years old.`); |
在 ES5 中,需要换行时,需要这样:
1 2 3 4 5 | var text = ( 'cat\n' + 'dog\n' + 'nickelodeon' ); |
模版字符串 可以支持换行并且不需要额外的处理:
1 2 3 4 | let text = ( `cat dog nickelodeon` ); |
模版字符串 还支持表达式:
1 2 | let today = new Date(); let text = `The time and date is ${today.toLocaleString()}`; |
手机阅读请扫描下方二维码:
上一篇:HTML5的history API和浏览器历史记录管理
下一篇:深入了解DOM对象
12345678

1
1
1
1
1
1
1
1
1
1
1
1
1
1
12345678

12345678
12345678
12345678
12345678
12345678

12345678

1
12345678

12345678

1

1

1

1

1

1

1

1

1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1
1