找出一个字符串中某个字串出现的所有位置

2023-11-03

在一个字符串中找出某个目标字串出现的所有位置,有哪些方法?我目前能想到的是这2种:

方法一:
function findAllIndex(str, char) {
const positions = [];
let index = str.indexOf(char);
while (index !== -1) {
positions.push(index)
index = str.indexOf(char, index + char.length);
}
return positions;
}

方法二:

function findAllIndex(str, char) {
const pattern = new RegExp(char, ‘g’);
const positions = [];
str.replace(pattern, function() {
positions.push(arguments[1]);
});
return positions;
}

const str = ‘hello world, hello world’;
console.log(findAllIndex(str, ‘world’)); // [6, 19]

不知道还有哪些好方法,想到了再来补充。

发表评论

邮箱地址不会被公开。 必填项已用*标注