学习笔记 JavaScript ES6 字符串的扩展

学习内容:

  • 字符串的unicode表示法
  • 字符串的遍历器接口
  • 模板字符串 (反引号``)
  • String.fromCodePoint()
  • String.prototype.includes()
  • String.prototype.startsWith()
  • String.prototype.endsWith()
  • String.prototype.repeat()

上面几个方法不带prototype的方法是静态方法,有prototype是实例方法。

unicode表示法

表示一个字符的几种方法:

  1. z,直接写出字符串
  2. \u{码点} (ES6中这样使用码点)
  3. \HHH,八进制
  4. \xHH,十六进制
  5. \u0000~ffff (ES5中这样使用码点,且码点不能大于四个f)

字符串的遍历

let s = 'world'
for(item of s) {
    console.log(item)
}

-------
w
o
r
l
d

模板字符串

ES6中对单引号和双引号不作区分。

使用反引号实现字符串的换行:

// ES5的写法
let str1 = '这是第一行\n'
+'这是第二行\n'
+'这是第三行'

console.log(str1)

// ES6的写法
let str2 = `这是第一行
这是第二行
这是第三行`

console.log(str2)

-------------------
这是第一行
这是第二行
这是第三行

这是第一行
这是第二行
这是第三行

有了反引号,输出html文本代码就很方便了。

再来看个例子:

模板字符串是的变更用${ 变量名称 }

const a = 30
const b = 70
const c = '元'

let str1 = '请计算30+70等于:' + (a + b) + c // 很容易写错
console.log(str1)

let str2 = `请计算30+70等于:${a + b}${c}` // 使用模板字符串就好很好
console.log(str2)

---------------------------
请计算30+70等于:100元 
请计算30+70等于:100元

嵌套模板的例子 

场景:html定义的属性不是固定的,比如class是经过逻辑运算得到的。这里举一个根据屏幕大小动态得到icon big 还是icon small的例子:

const isLargeScreen = () => {
    return true
}
let class1 = 'icon'

// ES5实现方式
class1 += isLargeScreen() ? ' icon-big' : ' icon-small'
console.log(class1)

// ES6模板字符串
const class2 = `icon icon-${isLargeScreen() ? 'big' : 'small'}`
console.log(class2)

-----------------------
icon icon-big
icon icon-big

带标签的模板字符串

注意:

1、方法里传递模板字符串时,要直接传递,不需要括号

2、输出的:raw: (3) ['我是', ',我的年龄是', '岁']被称为原始字符串

const func = (a, b, c, d) => {
    console.log(a)
    console.log(b)
    console.log(c)
    console.log(d)
}

const name = 'Sure'
const age = 36

func`我是${name},我的年龄是${age}岁` // 向方法里传递模板字符串时,要直接传递,不需要括号

--------------------------------------------------
(3) ['我是', ',我的年龄是', '岁', raw: Array(3)] 
    0: "我是"
    1: ",我的年龄是"
    2: "岁"
    length: 3
    raw: (3) ['我是', ',我的年龄是', '岁']
Sure
36
undefined

String.fromCodePoint()

console.log(String.fromCharCode(0x20BB7)) //ES5
console.log(String.fromCodePoint(0x20BB7))

------------------------------
ஷ // ES5无法识别,因为大于ffff
𠮷 // ES6可以

String.prototype.includes() 

返回是否包含某字符串,返回boolean类型

String.prototype.startsWith()、String.prototype.endsWith()

以谁开头,以谁结尾,返回boolean类型

String.prototype.repeat()

重复拼接字符串

const str = 'string '
const newStr = str.repeat(10) // 重复10次
console.log(newStr)
 
-------------------------------------------------------------------------
string string string string string string string string string string 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值