JS匹配字符串中所有出现的子字符串

时间:2018-11-05 21:55:30

标签: javascript

我看过此链接,但是我的问题不同。 javascript regex match all occurrences of substring?

match()中的

JS函数可用于匹配字符串中的子字符串。

运行这段代码时,我得到了这样的输出。

let s = 'Hello_HaHaHaHackerRank';
let hacker = s.match('HaHa');
console.log(hacker);
console.log(hacker.index);
console.log(hacker.input);

输出:

["HaHa"]
6
Hello_HaHaHaHackerRank

hacker.index给出了该模式的第一次出现。但是该字符串有3次HaHa。一个在index 6,另一个在index 8,另一个在index 10

任何人都可以解释一下,如何获得所有子串的出现?

2 个答案:

答案 0 :(得分:2)

indexOf具有 fromIndex 值,您可以将其用于while循环str.indexOf(searchValue[, fromIndex])

let s = 'Hello_HaHaHaHackerRank';
let find = 'HaHa'
let hacker = [];
let i = 0, j=0;
while (~(i = s.indexOf (find,i + find.length))) hacker.push(i);
console.log (hacker)

如果要包括所有出现的内容,请不要添加单词的长度。

while (~(i = s.indexOf (find,++i))) hacker.push (i)

答案 1 :(得分:0)

尝试:

$
相关问题