这一部分主要介绍Es6
中的字符串相关扩展。
2-1.子串识别
字符串中的子串识别,我们之前通常利用 indexOf()
的方法来判断:
js
function includes(str, subStr) {
return str.indexOf(subStr) > -1
}
var str = 'nice job'
console.log(includes(str, 'nice'))
在 Es6
中又新增了3个方法来更优雅的实现。
includes()
,如果在字符串中检测到指定文本则返回true
,否则返回false
。startsWith()
,如果在字符串的起始部分检测到指定文本则返回true
,否则返回false
。endsWith()
,如果在字符串的结束部分检测到指定文本则返回true
,否则返回false
。
譬如:
js
var str = 'nice job' // 字符串索引为0-7
// includes
console.log(str.includes('nice')) // true
// startsWith
console.log(str.startsWith('nice')) // true
console.log(str.startsWith('ice')) // false
// endsWith
console.log(str.endsWith('job')) // true
console.log(str.endsWith('jo')) // false
// 另外这些方法都支持第二个参数,代表的是文本开始检测的位置。
console.log(str.includes('job', 4)) // true
console.log(str.startsWith('ice', 1)) // true
endsWith
的第二个参数较为特殊,它内部使用的是 substring
方法,所以截取时不包含末位字符串。譬如:
js
// 索引为0-7
var str = 'nice job'
// 截取结果为 'nice jo',不包含 'b'
console.log(str.endsWith('job', 7)) // false
console.log(str.endsWith('jo', 7)) // true
// 截取结果为 'nice job'
console.log(str.endsWith('job', 8)) // true
此外,endsWith
的低版本 polyfill
如下:
js
if (!String.prototype.endsWith) {
String.prototype.endsWith = function(search, this_len) {
if (this_len === undefined || this_len > this.length) {
this_len = this.length;
}
return this.substring(this_len - search.length, this_len) === search;
}
}
TIP
str.substring(indexStart[, indexEnd])
indexStart
需要截取的第一个字符的索引,该索引位置的字符作为返回的字符串的首字母。indexEnd
可选。一个 0 到字符串长度之间的整数,以该数字为索引的字符不包含在截取的字符串内。
2-2.多行字符串
JS
中的字符串,如果使用单、双引号,字符串一定要在同一行才行。
如果你直接写如下的代码并执行:
js
var multiStr = 'multiline
string'
会报错 Uncaught SyntaxError: Invalid or unexpected token
.
先介绍下 Es6
版本之前的解决方案。
解决报错的方式是:
①在利用反斜杠转译掉行与行之间的空白段落换行符。
js
var multiStr = 'multiline \
string'
②手动添加换行符。
js
var multiStr = 'multiline\n\
string'
console.log(multiStr) //multiline
//string
当然也可以使用其他办法来实现上述效果:
js
var list = ['multiline', 'string']
var multiStr = list.join('\n')
console.log(multiStr)
// or
var multiStr = 'multiline\n' + 'string'
console.log(multiStr)
在 Es6
中提供了模板字符串来更优雅的解决这种情况,使用方式就是利用反引号:
js
var multiStr = `multiline
string`
console.log(multiStr)
2-3.字符串变量占位符
模板字符串更高级的功能是能够嵌入变量:
js
var a = 'hello'
var str = `${a} world`
// 其实${}符号不止支持变量,它还支持表达式
var judgeStr = `${Math.random() > 0.5 ? a : 'bye'} world`
console.log(str)
console.log(judgeStr)