JS Match all occurrences of substring in a string

后端 未结 2 1867
暗喜
暗喜 2021-01-25 08:07

I have seen this link but my question is different. javascript regex match all occurrences of substring?

match() function in JS can be used to

相关标签:
2条回答
  • 2021-01-25 08:27

    Try with:

    let re = /HaHa/g,
    str = "Hello_HaHaHaHackerRank";
    while ((match = re.exec(str)) != null) {
      console.log("match found at " + match.index);
    }
    
    0 讨论(0)
  • 2021-01-25 08:37

    indexOf has a fromIndex value you can use with a while loop 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)

    If you want to include all occurences, don't add the length of the word.

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

    0 讨论(0)
提交回复
热议问题