这是我参与8月更文挑战的第18天,活动详情查看:8月更文挑战
es6与es5有很多的不同,改进及增加了很多方法,像const let箭头函数等等
这篇文章我们介绍一下es6新增的字符串方法
raw
ES6 还为原生的 String 对象,提供了一个
raw()方法。该方法返回一个斜杠都被转义(即斜杠前面再加一个斜杠)的字符串,往往用于模板字符串的处理方法。
String.raw`Hello\n${7+8}.`
// 实际返回 "Hello\n15.",显示的是转义后的结果 "Hello\n15."
String.raw`Hello\liming!`;
// 实际返回 "Hello\liming!",显示的是转义后的结果 "Hi\liming!"
如果原字符串的斜杠已经转义,那么String.raw()会进行再次转义。
String.raw`hello\n`
// 返回 "hello\\n"
String.raw`hello\n` === "hello\\n" // true
includes(), startsWith(), endsWith()
- includes()返回布尔值,表示是否找到了参数字符串
- startsWith()返回布尔值,表示参数字符串是否在源字符串的头部
- endsWith()返回布尔值,表示参数字符串是否在源字符串的尾部
let str="xyz";
//字符串是否以某个字符开头
console.log(str.startsWith('x'));//true
console.log(str.startsWith('y'));//false
//字符串是否以某个字符结尾
console.log(str.endsWith('y'));//false
console.log(str.endsWith('z'));//true
//字符串是否包含某个字符
console.log(str.includes('y'));//true
console.log(str.includes('a'));//false
//repeat()重复某个字符串几次
console.log(str.repeat(3));//xyzxyzxyz
console.log(str.repeat(5));//xyzxyzxyzxyzxyz
实例方法:repeat()
repeat方法返回一个新字符串,表示将原字符串重复n次。
'x'.repeat(5) // "xxxxx"
'hi'.repeat(2) // "hihi"
'na'.repeat(0) // ""
-
注意
repeat()的参数不能为负数或者Infinity,如果repeat的参数是负数或者Infinity,会报错。 -
但是,如果参数是 0 到-1 之间的小数,则等同于 0,这是因为会先进行取整运算。0 到-1 之间的小数,取整以后等于
-0,repeat视同为 0。