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中处理字符串的方法,希望对你日常开发有所帮助。