ES6对字符串新增了一些函数和操作规范,使得开发者对字符串的操作更加方便,以往需要借助其他javascript代码才能实现的效果,现在利用这些函数即可快速实现。
模板字符串
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
let name = 'zhangsan' let age = '30' let str = 'he is ' + name +',' + 'age '+ age ; console.log(str)
es6拼接
let str2 = `he is ${name},age is ${age}` console.log(str2)
es6中可直接对字符串换行
let str3 = `write once , write once`; console.log(str3)
|
${}中可以放任意JavaScript表达式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| var a = 1; var b = 2; var total = ` is ${a+b}` console.log(total)
var obj = {'as':11 , 'bs':22} var strs = ` is ${obj.as} and ${obj.bs}` console.log(strs)
function fn(){ return 3 } var stra = `is ${ fn() }` console.log(stra)
|
标签模板
标签模板简单的理解就是:“标签”指的就是函数,紧跟在后面的模板字符串就是它的参数。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| alert`123`
alert(123)
var names = 'lxm'; var ages = '18';
tagFn`我${names},age${ages}`; function tagFn(arr,v1,v2){ console.log(arr) console.log(v1) console.log(v2) }
|
repeat()函数
1 2 3 4
| var strs = 'lxm'; var strs2 = strs.repeat(2); console.log(strs2)
|
includes()函数
1 2 3 4 5 6 7 8
|
var tit = '我是一个前端工程师'; var tits = tit.includes('前'); var tits2 = tit.includes('前',6); console.log(tits) console.log(tits2)
|
startsWith()函数
1 2 3 4 5 6 7 8 9
|
var titer = '前端开发工程师'; var titer1 = titer.startsWith('前'); var titer2 = titer.startsWith('端'); var titer3 = titer.startsWith('端', 1); console.log(titer1) console.log(titer2) console.log(titer3)
|
endsWith()函数
1 2 3 4 5 6
|
var tname = '我是一枚美女'; console.log(tname.endsWith('女')) console.log(tname.endsWith('我')) console.log(tname.endsWith('我',2))
|
codePointAt()函数 返回十进制数
1 2 3 4 5 6 7 8 9 10 11 12
|
var stri2 = '𠮷'; console.log(stri2.charAt(0)) console.log(stri2.codePointAt())
console.log(String.fromCodePoint(134071))
|
String.raw``函数
不用括号用反引号即直接加模板字符串
1 2 3 4 5 6 7 8 9 10
|
console.log(`hello\nworld`); console.log(String.raw`hello\nworld`);
var stt = '𠮷'; var stt2 = stt.codePointAt() console.log(String.fromCodePoint(stt2))
|