【Javascript修炼篇】JS中字符串操作整理

1. indexOf

inputStr.indexOf(str) — 返回给定 inputStr 中提到的 str 的首次出现位置。

inputStr.indexOf(str, 10) — 返回从第 10 个位置之后 str 的首次出现位置。

const str = 'Hi, Welcome to Vishwaks JS articles';

str.indexOf('Welcome');
> 4

str.indexOf('Welcome', 10); // 在第 10 个位置之后查找。
> -1

const str = 'Hi, Welcome to Vishwaks JS articles - Welcome to JustCode';

str.indexOf('Welcome', 10); // 在第 10 个位置之后查找。
> 38

str.indexOf('hi'); // 区分大小写
> -1

2. lastIndexOf

这跟 indexOf 类似,但是它从字符串的末尾开始搜索。

inputStr.lastIndexOf(str) — 返回给定 inputStr 中提到的 str 的最后一次出现位置。

inputStr.lastIndexOf(str, 10) — 返回从第 10 个位置到开头 str 的最后一次出现位置。

const testString = "locate string locate";

testString.lastIndexOf('locate');
> 14

testString.lastIndexOf('locate', 14);
> 14

testString.lastIndexOf('string');
> 7

testString.lastIndexOf('string', 6);
> -1

testString.lastIndexOf('string', 15);
> 7

testString.lastIndexOf('String'); // 区分大小写
> -1

3. search

search() 方法与 indexOf 类似,但不允许指定位置参数。

而且,indexOf 不支持基于正则表达式的搜索,但 search() 支持。

const str = 'Hi, Welcome to Vishwaks JS articles 1234';

str.search('Welcom');
> 4

str.search(/\d/);
> 36

str.search(1234);
> 36

str.search('welcome'); // 区分大小写
> -1

4. match

match() 方法类似于 search,但它返回一个包含匹配字符串的数组。

const str = 'Hi, Welcome to Vishwaks JS articles 1234';

str.match('Hi');
> ['Hi', index: 0, input: 'Hi, Welcome to Vishwaks JS articles 1234', groups: undefined]

str.match('Welcome');
> ['Welcome', index: 4, input: 'Hi, Welcome to Vishwaks JS articles 1234', groups: undefined]

str.match(/\d/);
> ['1', index: 36, input: 'Hi, Welcome to Vishwaks JS articles 1234', groups: undefined]

str.match('hi'); // 区分大小写
> null

5. includes

includes() 如果找到字符串,则返回 true。

const str = 'Hi, Welcome to Vishwaks JS articles 1234';

str.includes(1234);
> true

str.includes('JS');
> true

str.includes('test');
> false

str.includes('hi'); // 区分大小写
> false

6. startsWith

如果字符串以指定值开头,则返回布尔值。

str.startsWith('test') — 如果 ‘str’ 以 ‘test’ 开头,则返回 true 否则返回 false。

str.startsWith('test', 10) — 检查字符串的第 10 个索引是否以 test 开头。

const str = 'Hi, Welcome to Vishwaks JS articles';

str.startsWith('Hi');
> true

str.startsWith('Welcome', 4);
> true

str.startsWith('hi'); // 区分大小写
> false

7. endsWith

如果字符串以指定值结尾,则返回布尔值。

str.endsWith('test') — 如果 ‘str’ 以 ‘test’ 结尾,则返回 true 否则返回 false。

str.endsWith('test', 10) — 检查字符串直到第 10 个索引是否以 test 结尾。

const str = 'Hi, Welcome to Vishwaks JS articles';

str.endsWith('articles');
> true

str.endsWith('to', 14); // 检查前 14 个字符是否以 'to' 结尾。
> true

str.endsWith('aRticles'); // 区分大小写
> false

还有两个来自 RegExp 的方法 test()exec(),它们的作用也类似。

以上所有方法都是区分大小写的。

今天,我们学习了7中JS中处理字符串的方法,希望对你日常开发有所帮助。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值