3.String扩展

126 阅读1分钟

ES6对String类型作了一些扩展,本文主要介绍最重要的两个

1.模板字符串

ES6引入了模板字符串${exp},可以在{}里面插入变量,从而避免了字符串的繁杂操作。

没有模板字符串之前,一些功能写起来很机车:

var profile = document.getElementById('profile')
user = { name: '肖宇晨', info: '这个人除了帅,一无是处'}
profile.innerHTML =
  '<h1>' + user.name + '</h1>' +
  '<p>' + user.info + '</p>'

现在引入模板字符串,明显舒适多了~

profile.innerHTML = `
  <h1> ${user.name} </h1>
  <p> ${user.info} </p>
`

在模板中也可以调用函数

function getCoolBoy() {
  return '韦兴奇'
}
`彭于晏 ${getCoolBoy()} 吴彦祖` // 彭于晏 韦兴奇 吴彦祖

还可以花式调用

let friends = [
  {name:'jack' ,id:1},
  {name:'tom' ,id:2}
]
const getFriends = friends =>`
<ul>
  ${
     friends.map(friend=>`
       <li>${friend.id}</li>
       <li>${friend.name}</li>
     `).join('')
   }
</ul>
`
var profile = document.getElementById('profile')
profile.innerHTML = getFriends(friends)

2.扩展方法

ES6对String的原型上进行了方法扩展,以下是常用的:

includes(str, index) // 从index开始检测是否含有str字符串,index默认为0
replaceAll(str, newStr) // 将子字符串str全部替换为newStr,等价于: replace(/str/g, newStr),这里用了正则

fromCharCode(unicode) // 将unicode码点返回对应字符
startsWith(str, index) // 从index开始检测是否以str字符串开头
endsWith(str, index) // 你猜猜~

repeat(n) // 将字符串重复n遍并返回
padStart(len, str) / padLeft(len, str) // 检测字符串是否满足len长度,若不满足在其前方用子字符串str补全
padEnd(len, str) / padRight(len, str) // 你懂的~

trim() // 去除前后空格
trimLeft() / trimStart() // 你猜猜~
trimRight() / trimEnd() // 你猜猜~