hand
_1_11_275
4
返回栏目
0k
2k
1k
2k
1k
1k
1k
2k
2k
2k
1k
2k
1k
2k
1k
1k
1k
1k
1k
2k
1k
1k
1k
1k
1k
1k
1k
1k
1k
2k
1k
1k
1k
1k
1k
1k
1k
1k
1k
2k
1k
1k
1k
1k
1k
1k
1k
2k
1k
2k
1k
1k
1k
1k
1k
1k
1k
2k
2k
1k
1k
1k
2k
1k
1k
2k
2k
1k
1k
1k
2k
1k
1k
2k
2k
1k
2k
1k
1k
2k
2k
2k
3k
3k
2k
3k
2k
3k
3k
3k
1k
2k
3k
2k
2k
3k
3k
2k
2k
6k
3k
2k
2k
5k
3k
4k
3k
3k
2k
4k
3k
3k
2k
3k
3k
1k
4k
4k
4k
2k
5k
3k
2k
3k
4k
3k
3k
4k
2k
3k
3k
4k
2k
2k
3k
4k
3k
3k
2k
5k
2k
3k
3k
3k
3k
2k
3k
3k
3k
2k
2k
2k
2k
3k
2k
2k
2k
3k
2k
2k
2k
2k
2k
2k
0.1k
0.2k
3k
2k
3k
2k
0.1k
2k
2k
4k
2k
2k
1k
2k
2k
3k
3k
3k
3k
2k
2k
3k
3k
3k
4k
3k
3k
4k
3k
2k
2k
3k
3k
3k
3k
3k
3k
2k
3k
3k
4k
4k
3k
3k
2k
2k
3k
2k
2k
1k
2k
3k
1k
2k
2k
2k
2k
2k
2k
2k
2k
2k
4k
2k
3k
2k
1k
2k
2k
2k
2k
2k
3k
2k
3k
1k
2k
2k
2k
0k
2k
2k
2k
2k
2k
2k
2k
3k
2k
2k
1k
1k
3k
2k
3k
1k
2k
1k
2k
2k
2k
2k
3k
1k
3k
2k
2k
2k
2k
2k
2k
1k
2k
2k
4k
3k
3k
2k
2k
2k
2k
2k
2k
4k
3k
3k
3k
2k
2k
2k
2k
2k
2k
3k
4k
返回前端 - Javascript栏目
作者:
贺及楼
成为作者
更新日期:2025-02-21 21:14:58
在前端开发中,字符串匹配是一项非常常见且重要的任务。有时候,我们不仅仅需要找到字符串中的第一个匹配项,还需要找出所有的匹配结果,并对这些多匹配结果进行有效的处理。本文将详细介绍在 JavaScript 中如何实现字符串的全匹配以及对多匹配结果的处理。
在 JavaScript 中,正则表达式是进行字符串匹配的强大工具。要实现全匹配,我们可以使用正则表达式的全局匹配标志 g
。
const str = "Hello, hello, world! Hello again.";
const regex = /hello/gi; // i 标志表示忽略大小写,g 标志表示全局匹配
const matches = str.match(regex);
console.log(matches);
regex = /hello/gi
:创建了一个正则表达式,hello
是要匹配的模式,g
表示全局匹配,即会找出字符串中所有匹配的项;i
表示忽略大小写,这样 Hello
、hello
等都会被匹配到。str.match(regex)
:调用字符串的 match
方法,传入正则表达式作为参数,该方法会返回一个包含所有匹配结果的数组。
[ 'Hello', 'hello', 'Hello' ]
const str = "Hello, hello, world! Hello again.";
const regex = /hello/gi;
const matches = str.match(regex);
if (matches) {
const count = matches.length;
console.log(`匹配结果的数量为: ${count}`);
} else {
console.log('没有找到匹配结果');
}
match
方法获取所有匹配结果的数组 matches
。matches
是否存在,如果存在则通过 length
属性获取匹配结果的数量;如果不存在则表示没有找到匹配结果。
const str = "Hello, hello, world! Hello again.";
const regex = /hello/gi;
const newStr = str.replace(regex, 'Hi');
console.log(newStr);
replace
方法,传入正则表达式和替换字符串作为参数。replace
方法会将字符串中所有匹配正则表达式的部分替换为指定的字符串。
Hi, Hi, world! Hi again.
const str = "Hello, hello, world! Hello again.";
const regex = /hello/gi;
const indices = [];
let match;
while ((match = regex.exec(str))!== null) {
indices.push(match.index);
}
console.log('匹配结果的索引位置:', indices);
exec
方法进行循环匹配。exec
方法会在每次调用时返回一个包含匹配信息的数组,其中 index
属性表示匹配结果在字符串中的起始索引位置。exec
方法返回 null
时,表示已经没有更多的匹配结果了。
匹配结果的索引位置: [ 0, 7, 21 ]
操作 | 方法 | 示例代码 |
---|---|---|
全匹配 | match |
const matches = str.match(regex); |
统计数量 | length |
const count = matches.length; |
替换所有匹配结果 | replace |
const newStr = str.replace(regex, 'Hi'); |
获取匹配结果的索引位置 | exec |
while ((match = regex.exec(str))!== null) { indices.push(match.index); } |
通过以上方法,我们可以在 JavaScript 中轻松实现字符串的全匹配,并对多匹配结果进行各种处理。这些技巧在前端开发中非常实用,例如在搜索功能、文本替换等场景中都能发挥重要作用。
前端 - Javascript
整章节共299节
快分享给你的小伙伴吧 ~