ES6 字符串干货

1次阅读

共计 1528 个字符,预计需要花费 4 分钟才能阅读完成。

摘取出 ES6 中字符串的新增干货「摘自 http://es6.ruanyifeng.com/」
牛逼之处
模板字符串
1. 可写多行字符串
2. 使用 ${} 添加变量
let x = 1;
let y = 2;

`${x} + ${y} = ${x + y}`
// “1 + 2 = 3”

`${x} + ${y * 2} = ${x + y * 2}`
// “1 + 4 = 5”

let obj = {x: 1, y: 2};
`${obj.x + obj.y}`
// “3”
模板字符串之中还能调用函数
function fn() {
return “Hello World”;
}

`foo ${fn()} bar`
// foo Hello World bar
模板字符串甚至还能嵌套
const tmpl = addrs => `
<table>
${addrs.map(addr => `
<tr><td>${addr.first}</td></tr>
<tr><td>${addr.last}</td></tr>
`).join(”)}
</table>
`;
标签模板:
let total = 30;
let msg = passthru`The total is ${total} (${total*1.05} with tax)`;

function passthru(literals) {
let result = ”;
let i = 0;

while (i < literals.length) {
result += literals[i++];
if (i < arguments.length) {
result += arguments[i];
}
}

return result;
}

msg // “The total is 30 (31.5 with tax)”
literals 参数为非变量组成的数组,变量原本位置为数组中各元素之间,上面这个例子展示了,如何将各个参数按照原来的位置拼合回去。

“标签模板”的一个重要应用,就是过滤 HTML 字符串,防止用户输入恶意内容。

实用方法集
1. 字符串的遍历器接口
for (let codePoint of ‘foo’) {
console.log(codePoint)
}
// “f”
// “o”
// “o”
2.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
上面代码表示,使用第二个参数 n 时,endsWith 的行为与其他两个方法有所不同。它针对前 n 个字符,而其他两个方法针对从第 n 个位置直到字符串结束。
3.repeat()
repeat 方法返回一个新字符串,表示将原字符串重复 n 次。
‘x’.repeat(3) // “xxx”
‘hello’.repeat(2) // “hellohello”
‘na’.repeat(0) // “”
4.padStart(),padEnd()
padStart()
用于头部补全,
padEnd()
用于尾部补全。
‘x’.padStart(5, ‘ab’) // ‘ababx’
‘x’.padStart(4, ‘ab’) // ‘abax’

‘x’.padEnd(5, ‘ab’) // ‘xabab’
‘x’.padEnd(4, ‘ab’) // ‘xaba’
’12’.padStart(10, ‘YYYY-MM-DD’) // “YYYY-MM-12”
’09-12′.padStart(10, ‘YYYY-MM-DD’) // “YYYY-09-12”

正文完
 0