ES6学习第三节:字符串的扩展

  • 字符串遍历

for ... of

// 字符串遍历
const txt = 'www.coffeecola.cn'
for (var item of txt) console.log(item)
  • includes startsWith endsWith

includes():返回布尔值,表示是否找到了参数字符串。
startsWith():返回布尔值,表示参数字符串是否在原字符串的头部。
endsWith():返回布尔值,表示参数字符串是否在原字符串的尾部。

// includes startsWith endsWith
console.log(txt.includes('coffeecola'))
console.log(txt.startsWith('www'))
console.log(txt.endsWith('cn'))
  • repeat

repeat方法返回一个新字符串,表示将原字符串重复n次。

// repeat
console.log(txt.repeat(0.1))
console.log(txt.repeat(2))
// 取整
console.log(txt.repeat(2.9))
  • padStart padEnd

字符串补全长度的功能

// padStart padEnd
console.log(txt.padStart(txt.length + 8, 'https://'))
console.log(txt.padEnd(txt.length + 8, '/#/login'))
  • matchAll

Node v10.8.0不支持

var reg = /o/
console.log(txt.match(reg))
// Node不支持 v10.8.0
// console.log(txt.matchAll(reg));
var reg = /o/g
console.log(txt.match(reg))
  • 字符串模板
var name = 'ChangLau'
var str = `
  \`Hello, my Name is ${name}\`
`
console.log(str)
var a = 1,
  b = 2
// 模板字符串可以进行JS运算
console.log(`${a} add ${b} equals ${a + b}`)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容