此分类为学习ECMAScript 6的笔记,主要参考《ECMAScript 6 入门》
ECMAScript6对字符串进行了一系列的扩展。
字符串遍历器接口
ECMAScript6为字符串提供了遍历器接口,使得字符串可以进行for...of...循环。
for (let i of "foo") { console.log(i); } // "f" // "o" // "o"
这个遍历器可以识别大于 0xFFFF 的码点,传统的 for 循环无法识别。
includes(), startsWith(), endsWith()
传统上,javascript只有 indexOf 方法确定一个字符串是否包含某字符。ES6 提供了3种新方法。
includes() 返回布尔值,表示是否找到了参数字符串。
startsWith() 返回布尔值,表示参数字符是否在字符串头部。
endsWith() 返回布尔值,表示参数字符是否在字符串头部。
三种方法都支持第二个参数,表示开始搜索的位置。
let s = "Hello World!"; s.startsWith("World", 6); // true s.endsWith("Hello", 5); // true s.endsWith("Hell", 4); // true s.includes("Hello", 6); // false
repeat()
repeat 方法会返回一个字符串,表示将原字符串重复 n 次。
"hello".repeat() // "" "hello".repeat(2) // "hellohello" "hello".repeat("2") // "hellohello" "hello".repeat("h") // "" "hello".repeat(2.5) // "hellohello" "hello".repeat(-1) // Uncaught RangeError: Invalid count value "hello".repeat(-0.5) // "" "hello".repeat(Infinity) // Uncaught RangeError: Invalid count value "hello".repeat(NaN) // ""
参数若非数字,会先转化为数字。参数是负数会报错。参数为小数,需要先取整,所以-1——0时返回空字符串。NaN 等同于0.
模版字符串
ES6 引入了模版字符串,增强版的字符串,用反引号(`)标识。
模版字符串可以直接定义多行字符串。会保留所有空格和缩进。
$('#result').append(` There are <b>${basket.count}</b> items in your basket, <em>${basket.onSale}</em> are on sale! `);
可以在中间嵌入变量和任意表达式,还能调用函数。
let name = "bill", age = 24; let s = `${name} is ${age} years old` // "bill is 24 years old" let t = `1 + 2 = ${1 + 2}` // "1 + 2 = 3"
padStart(), padEnt()
这两个方法用于补全字符串长度,如果字符串长度不够,会在头部或尾部补全。
'x'.padStart(5, 'ab') // 'ababx' 'x'.padStart(4, 'ab') // 'abax' 'x'.padEnd(5, 'ab') // 'xabab' 'x'.padEnd(4, 'ab') // 'xaba'
该方法需要传入两个参数,第一个参数是生成的字符串的最小长度,第二个参数是用来补全的字符串。
如果原字符串大于等于传入的长度,则返回原字符串。
'xxx'.padStart(2, 'ab') // 'xxx' 'xxx'.padEnd(2, 'ab') // 'xxx'
如果忽略第二个参数,则默认用空格补全
'xxx'.padStart(6) // ' xxx' 'xxx'.padEnd(7) // 'xxx '
// String.raw()
// 该方法用来得到原生的String对象。
// 这个方法往往用来充当模板字符串的处理函数,返回一个斜杠都被转义的字符串