第3章 字符串的扩展

查询是否包含某一字符

let string = 'my name is tabBin'
string.indexOf(tabBin) // 11
string.includes('tabBin') // true
string.startWith('m') // true
string.endWith('m') // false, 应该是n

repeat()

repeat方法返回一个新字符串,表示将原来的字符串重复几次

let s = 'hello'
let new = s.repeat(2)
console.log(new) // hellohello

如果参数为小数,会被取整;如果参数为负数或者infinity,会报错

let s = 'hello'
let new = s.repeat(2.7)
console.log(new) // hellohello

let new = s.repeat(-2) // 报错

模板字符串

模板字符串是增强版的字符串,用反引号(`)来表示。它可以当做普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。

let [name, age, sex]  = [' tanBin ', ' 22 ', ' 男 '  ]
let string = "我的名字是`${name}`,年龄是${age},性别是${sex}"
console.log(string) // 我的名字是tanBin,年龄是22,性别是男

其他

let s = 'hello world'
s.replace('o', 'mmm') // hellmmm  world,字符串替换
s.split(' ') // ['hello', 'world'] 字符串分割,分后为一个数组
s.trim() // 去空格

你可能感兴趣的:(第3章 字符串的扩展)