做有态度的前端团队

网易FEG前端团队

ES6实战——字符串

在 ES6 中,标准库升级了很多,在这些变化中有许多新的对于字符串的函数,比如 .includes() 和 .repeat()。

.includes( )

var string = 'food';
var substring = 'foo';

console.log(string.indexOf(substring) > -1); // true

之前我们使用 indexOf() 函数的返回值是否 >-1 来判断字符串是否包含某些字符串,现在我们更简单地使用 .includes() 来返回一个布尔值来判断:

const string = 'food';
const substring = 'foo';

console.log(string.includes(substring)); // true

.repeat( )

function repeat(string, count) {
    var strings = [];
    while(strings.length < count) {
        strings.push(string);
    }
    return strings.join('');
}

在 ES6 中,可以更简便地实现:

'meow'.repeat(3); // 'meowmeowmeow'

模版字符串

使用 模版字符串 我们就可以不用对某些特殊字符进行转义处理了:

var text = "This string contains \"double quotes\" which are escaped.";
let text = `This string contains "double quotes" which don't need to be escaped anymore.`;

模版字符串 还支持插入,可以把变量值和字符串连接起来.

var name = 'Tiger';
var age = 13;

console.log('My cat is named ' + name + ' and is ' + age + ' years old.');

还可以更简单:

const name = 'Tiger';
const age = 13;

console.log(`My cat is named ${name} and is ${age} years old.`);

在 ES5 中,需要换行时,需要这样:

var text = (
    'cat\n' +
    'dog\n' +
    'nickelodeon'
);

模版字符串 可以支持换行并且不需要额外的处理:

let text = ( `cat
dog
nickelodeon`
);

模版字符串 还支持表达式:

let today = new Date();
let text = `The time and date is ${today.toLocaleString()}`;

手机阅读请扫描下方二维码: