es6字符串

es6中对字符串操作时,会先将字符串转换成一个类似数组的一个对象,因为他是一个对象,所以通过他的length属性可以获得他的长度。

比如:

//将字符串转为类似数组的一个对象
let [ x , y , z ]= '123'
console . log ( x , y , z ) // 1 2 3



//既然说它是一个类似数组的一个对象,那么他的长度length属性可以这样获得
let { length }= '971211'
console . log ( length ) //6


字符串的方法:

//indexOf() es5中判断字符串中有没有指定字符,有返回该字符在字符串中出现的第一个索引




//includes() 判断字符串中有没有指定的字符,有的话返回true 没有返回false
//第二个参数:开始查找的索引,默认是0

let str = 'qwertyuiopasdfghjk'
let is = str . includes ( '2' ) //false
let it = str . includes ( 'k' ) //true
// console.log(it)

//startsWith() 是不是以某个字符作为开头
//endsWith() 是不是以某个字符作为结尾

let starts1 = str . startsWith ( 'q' ) //true
let starts2 = str . startsWith ( 'qwe' ) //true
let starts3 = str . startsWith ( 'ewq' ) //false

let ends1 = str . endsWith ( 'k' ) //true
let ends2 = str . endsWith ( 'ghjk' ) //true
let ends3 = str . endsWith ( 'kjhg' ) //false



//repeat(n) 将字符串重复n次返回 原字符串不变
/*
1.n如果是小数,则向下取整
2.n如果是负数&infinity 则报错
3.n如果是0->-1 之间的数 先向下取整运算结果为0 输出为空字符串''
4.n如果是NaN => 0 输出为空字符串''
5.n如果是数字字符串 会先将字符串转换为数字,然后再去运算
*/
let str2 = str . repeat ( 3 ) // qwertyuiopasdfghjkqwertyuiopasdfghjkqwertyuiopasdfghjk
console . log ( str2 )

//


模板字符串的使用:

比如向body中插入一段html代码


//以前的做法
let str = 'I LOVE YOU'
document . body . innerHTML = '<h1>' + str + '</h1>'



//es6 并且{}中可以运算
document . body . innerHTML = `<h1> ${ str } </h1>`




//模板字符串还有另一个功能 就是保留换行和空格
console . log ( 'hahhahah \n hahahahah' );

/*
hahhahah
hahahahah
*/
let str2 = `hahhaha
gagagagag
hahahahah`
console . log ( str2 )

/*
hahhaha
gagagagag
hahahahah
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

宋哈哈

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值