2-4 字符串的扩展

71 阅读1分钟

字符串的Unicode 表示法 字符串的遍历接口 字符串模板 String.formCodePoint() String.prototype.includes() String.prototype.startsWith() String.prototype.endsWith() String.prototype.repeat()

字符的 Unicode 表示法

  1. ES6 加强了对 Unicode 的支持,允许采用\uxxxx形式表示一个字符,其中xxxx表示字符的 Unicode 码点。

  2. 限于码点在\u0000~\uFFFF之间的字符。超出这个范围的字符,必须用两个双字节的形式表示。

  3. 直接在\u后面跟上超过0xFFFF的数值会理解错误。

  4. 改进方案,只要将码点放入大括号,就能正确解读该字符

  • 每一个字符都有对应的Unicode码

字符串的遍历

for(let item of 'xiaobai'){
    console.log(item)
}
  • 可以使用for of 去遍历

字符串模板

const a = 20
const b = 10
const str1 = '我的年龄是:' + a + b
console.log(str1)
const str1 = '我的年龄是:' + (a + b)
console.log(str2)
  • 在字符串里面有各种各样的拼接,但是遇到算法的时候需要用小括号括起来

嵌套模板

let isLargeScreen = () => {
return true
}
let class1 = 'icon'
class1 += isLargeScreen () ? ' icon-big' : ' icon-small'
console.log(class1)

const2 = `icon icon-${isLargeScreen() ? 'big': 'small'}`

带标签的模板字符串

const foo = (a, b, c, d) => {
console.log(a)
console.log(b)
console.log(c)
console.log(d)
}
// foo(1, 2, 3, 4)
const name = 'UU'
const age = 4
foo`这是${name}, 他的年龄是${age}${111}`
  • 有prototype说明是在当前实例方法,没有prototype 相当于是我们的静态方法

// ES5 提供的语法,用于识别Unicode码点

String.formCharCode()

// ES6 提供的语法,用于识别Unicode码点

String.formCodePoint()

// indexOf 是否包含某个字符串,包含的话返回当前下标,不包含返回 -1

// includes 判断是否包含某个字符串,返回布尔类型,true false

String.prototype.includes()

// 是否以某个字符串开头

String.prototype.startsWith()

// 是否以某个字符串结尾

String.prototype.endsWith()

// 重复字符串

String.prototype.repeat()