ES6对字符串进行了扩展:
1、includes():返回布尔值,表示是否找到了参数字符串
2、startsWith():返回布尔值,表示参数字符串是否在原字符串的头部
3、endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部
4、repeat方法返回一个新字符串,表示将原字符串重复n次。
5、模板字符串
案例:
// includes():返回布尔值,表示是否找到了参数字符串
// startsWith():返回布尔值,表示参数字符串是否在原字符串的头部
// endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部
//
let strst = "hellow word";
console.log('hellow == '+ strst.startsWith('hellow', 1)); // 指定从索引开始(false)
console.log('hellow == '+ strst.startsWith('hellow')); // true
console.log('word == ' + strst.endsWith('word')); // true,从后检索
console.log('includes == ' + strst.includes("o")); //true
// repeat方法返回一个新字符串,表示将原字符串重复n次。
console.log('x == %s', 'x'.repeat(3)); // xxx
console.log('hello == %s', 'hello '.repeat(2)); // hello hello
console.log('abc == %s', 'abc'.repeat(0)); // 空
console.log('abc == %s', 'abc'.repeat(1.5)); // 小数取整
//console.log('abc == %s', 'abc'.repeat(-1)); // Invalid count value
// 如果某个字符串不够指定长度,会在头部或尾部补全。padStart()用于头部补全,padEnd()用于尾部补全
console.log('x == %s', "x1".padStart(5, '12')); // 不够5位前面补充12, 结果:121x1
console.log('x == %s', "x1".padEnd(5, '12')); // 不够5位后面补充12, 结果:x1121
// 用来补全的字符串与原字符串,两者的长度之和超过了指定的最小长度,则会截去超出位数的补全字符串
console.log('abc == %s', "abc".padStart(5, 123456789)); // 12abc
// 如果第二个参数省略则是挂到全局
console.log(' abc == %s', "abc".padStart(5)); // abc
// 模板字符串
let htmlstr = '这是一段文字,马上要`\n`换行`<br/>`了'
console.log(htmlstr); //
let name = 'zs', title = 'lisi'
console.log(`name == ${name}, title == ${title}`); // name == zs, title == lisi
// alert `123`
网友评论