ES6中字符串的扩展

一、查找字符串

在ES5中,可以使用 indexOf 方法和 lastIndexOf 方法查找字符串:

let str = 'hello world';
alert(str.indexOf('o'));   // 4
alert(str.lastIndexOf('o'));   // 7
alert(str.lastIndexOf('z'));   // -1

 ES6中,又新增了3个方法用于特定字符的查找。

 

1、includes()

该方法传入一个字符串参数,然后返回一个布尔值,表示是否在指定字符串中找到了该字符串片段。

let str = 'hello';
console.log(str.includes('h'));   // true
console.log(str.includes('z'));   // false

 

2、startsWith()

该方法传入一个字符串参数,然后返回一个布尔值,表示是否在指定字符串开头找到了该字符串片段。

let str = 'hello';
console.log(str.startsWith('h'));   // true
console.log(str.startsWith('lo'));   // false

 

3、endsWith()

该方法传入一个字符串参数,然后返回一个布尔值,表示是否在指定字符串末尾找到了该字符串片段。

let str = 'hello';
console.log(str.endsWith('h'));   // false
console.log(str.endsWith('o'));   // true

 

二、操作字符串

1、repeat()

对一个字符串进行重复,返回一个新字符串。

let str = 'ha';
console.log(str.repeat(3));   'hahaha'

参数如果是小数,会被向下取整进行操作。

let str = 'ha';
console.log(str.repeat(2.9));   'haha'

参数如果是负数,会报错。

let str = 'ha';
console.log(str.repeat(-2));   // error

 

三、模板字符串

ES6引入了模板字符串,用反引号标识( ` ),主要功能有俩个。

1、定义多行字符串。

let str = `hello
hello
hello`;
console.log(str)
// hello
// hello
// hello

2、在字符中嵌入变量,把变量包裹在 ${} 中即可。

var username = 'tom';
alert(`hello ${username}`);   // hello tom

 

转载于:https://www.cnblogs.com/xlj-code/p/10348671.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值