ES6 | 字符串的扩展

167 阅读2分钟

Offer 驾到,掘友接招!我正在参与2022春招打卡活动,点击查看活动详情

ES系列文章

字符的unicode表示法

// unicode
// es6 \uxxxx 码点 0000~ffff
// \u20BB7 -> \u20BB+7
// \u{20BB7}
// \u{41} -> A

字符串遍历接口

  • ES6字符串增加了遍历器接口,使字符串可以被for...of循环遍历。
for(let item of 'hello'){
     console.log(item)
}

模板字符串

在js中使用 ('' 或 "") 来表示字符串。当作普通字符串使用,也可以定义多行字符串,或者在字符串中间嵌入变量使用。

const str1 = '阿斯顿发斯\n'
+ '蒂芬阿萨德法师法\n'
+ '师按时发顺丰'
console.log(str1);

模板字符串就是使用反引号 (`) 来代替普通字符串中的双引号或单引号。

const str3 = `阿斯顿发斯
蒂芬阿萨德法师法
师按时发顺丰`
console.log(str3);
//嵌入变量
const a = 20
const b = 14
const c = 'hello'
const str2 = '我的年龄是:' + (a + b) + ',我在讲' + c
console.log(str2)
const str5 = `我的年龄是:${a+b},我在讲${c}`
console.log(str5)
// 嵌套模板
const isLargeScreen = () => {
    return true
}
let class1 = 'icon'
class1 += isLargeScreen() ? ' icon-big':' icon-small'
console.log(class1)

const class2 = `icon icon-${isLargeScreen()?'big':'small'}`
console.log(class2)
  • 在模板字符串中嵌入变量,需要将变量名写在${}之中。
  • 大括号内部可以放入任意的 JavaScript 表达式,进行运算,引用对象属性
  • 模板字符串之中还可以调用函数。
  • 模板字符串中的变量没有声明,将会报错。

String.fromCodePoint()

一般情况下用在unicode中,不常用。

es5中indexOf方法,可以用来检索当前字符串中是否包含某个字符串。

String.prototype.includes()

  • includes() :返回布尔值,表示是否找到了参数字符串。
const str = 'hello'
// console.log(str.includes('el1'))

String.prototype.startsWith()

  • startsWith() :返回布尔值,表示参数字符串是否在源字符串的开头。
const str = 'hello'
console.log(str.startsWith('he'))

String.prototype.endsWith()

  • endsWith() :返回布尔值,表示参数字符串是否在源字符串的结尾。
const str = 'hello'
console.log(str.endsWith('ello'))

String.prototype.repeat()

  • repeat方法返回一个新字符串,表示将原字符串重复n次。重复几次括号内写几。
const str = 'hello'
const newStr = str.repeat(10)
console.log(newStr)

一个前端小白,若文章有错误内容,欢迎大佬指点讨论!