Strings and Regular Expressions - ECMAScript 6(2)
在这一章中,有很多不是非常常用的东西,暂时放一下,主要说的其实就是string提供的几个新的方法。
1.包含
1)传统方法indexOf/lastIndexOf,这个方法不仅可以用于字符串,也可以用于数组去重,非常好用
ES6提供The includes() method returns true if the given text is found anywhere within the string. It returns false if not.
ES6提供The startsWith() method returns true if the given text is found at the beginning of the string. It returns false if not.
ES6提供The endsWith() method returns true if the given text is found at the end of the string. It returns false if not.
when the second argument is omitted, includes() and startsWith() search from the beginning of the string, while endsWith() starts from the end. 这三个函数的第二个参数是字符串查找的起始位置,都是从左往右数确定位置,索引从0开始,但是其中endsWith()是确定位置后再从右边往左边查找。
var msg = "Hello world!";
console.log(msg.startsWith("Hello")); // true
console.log(msg.endsWith("!")); // true
console.log(msg.includes("o")); // true
console.log(msg.startsWith("o")); // false
console.log(msg.endsWith("world!")); // true
console.log(msg.includes("x")); // false
console.log(msg.startsWith("o", 4)); // true
console.log(msg.endsWith("o", 8)); // true
console.log(msg.includes("o", 8)); // false
2.重复
repeat方法返回一个新字符串,表示将原字符串重复n次。
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
3.模板字符串
// 字符串中嵌入变量
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`
// 如果在模板字符串中需要使用反引号,则前面要用反斜杠转义。
var greeting = `\`Yo\` World!`;
//ES6比较好的插入方式
$('#list').html(`
<ul>
<li>first</li>
<li>second</li>
</ul>
`.trim());
//大括号内部可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性。
var x = 1;
var y = 2;
`${x} + ${y} = ${x + y}`
// "1 + 2 = 3"
`${x} + ${y * 2} = ${x + y * 2}`
// "1 + 4 = 5"
var obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// 3
//模板字符串之中还能调用函数。
function fn() {
return "Hello World";
}
`foo ${fn()} bar`
// foo Hello World bar
4.标签模板
alert`123`
// 等同于
alert(123)
标签模板其实不是模板,而是函数调用的一种特殊形式。“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数。
//1).标签模板”的一个重要应用,就是过滤HTML字符串,防止用户输入恶意内容。
var message =
SaferHTML`<p>${sender} has sent you a message.</p>`;
function SaferHTML(templateData) {
var s = templateData[0];
for (var i = 1; i < arguments.length; i++) {
var arg = String(arguments[i]);
// Escape special characters in the substitution.
s += arg.replace(/&/g, "&")
.replace(//g, ">");
// Don't escape special characters in the template.
s += templateData[i];
}
return s;
}
//2).标签模板的另一个应用,就是多语言转换(国际化处理)。
i18n`Welcome to ${siteName}, you are visitor number ${visitorNumber}!`
// "欢迎访问xxx,您是第xxxx位访问者!"