1、字符串接口的遍历
ES6 为字符串添加了遍历器接口使得字符串可以被for...of
循环遍历。
for (let codePoint of 'foo') {
console.log(codePoint)
}
// "f"
// "o"
// "o"
2、包含
传统上,JavaScript 只有indexOf方法,可以用来确定一个字符串是否包含在另一个字符串中。ES6 又提供了三种新方法。
-
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
3、repeat
repeat方法返回一个新字符串,表示将原字符串重复n次。参数如果是小数,会被取整。如果repeat的参数是负数或者Infinity,会报错
'x'.repeat(3) // "xxx"
'hello'.repeat(2) // "hellohello"
'na'.repeat(0) // ""
'na'.repeat(2.9) // "nana"
'na'.repeat(Infinity)// RangeError
'na'.repeat(-1)// RangeError
4、padStart(),padEnd()
ES2017 引入了字符串补全长度的功能。如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全。
'x'.padStart(5, 'ab') // 'ababx'
'x'.padStart(4, 'ab') // 'abax'
'x'.padEnd(5, 'ab') // 'xabab'
'x'.padEnd(4, 'ab') // 'xaba'
如果省略第二个参数,默认使用空格补全长度。
'x'.padStart(4) // ' x'
'x'.padEnd(4) // 'x '
5、模板字符串
模板字符串中嵌入变量,需要将变量名写在${}
之中
6、子字符串
str.charAt(index);
返回子字符串,index
为字符串下标,index取值范围[0,str.length-1]
7、返回子字符串的unicode编码
str.charCodeAt(index)
; 返回子字符串的unicode编码,index取值范围同上
String.fromCharCode(num1,num2,...,numN)
; 根据unicode编码返回字符串
8、 返回子字符串第一次出现的位置
str.indexOf(searchString,startIndex)
; 返回子字符串第一次出现的位置,从startIndex开始查找,找不到时返回-1
str.lastIndexOf(searchString,startIndex)
; 从由往左找子字符串,找不到时返回-1
9、截取字符串
str.substring(start,end)
; 两个参数都为正数,返回值:[start,end) 也就是说返回从start到end-1的字符
str.slice(start,end)
; 两个参数可正可负,负值代表从右截取,返回值:[start,end) 也就是说返回从start到end-1的字符
不建议用:str.substr(start,length)
; start参数可正可负,负数代表从右截取
除了 slice() 和 substr() 方法里的负值是代表从右截取,其他方法里的负值一律作为0处理
10、字符串的替换
str.replace(rgExp/substr,replaceText)
返回替换后的字符串
11、字符串分割成数组
str.split(separator,limit)
; 参数1指定字符串或正则,参照2指定数组的最大长度
例:str.split(""); 每个字符都被分割 ['','','','']
str.split(); 整个字符串放到数组里 ['']
【引申】:数组变成字符串
arr.join(分隔符) 以,连接
arr.join('') 无缝连接
arr.join('-') 以-连接
网友评论