How to get all indexes of a pattern in a string?

后端 未结 6 450
轮回少年
轮回少年 2021-01-18 19:56

I want something like this:

\"abcdab\".search(/a/g) //return [0,4]

Is it possible?

6条回答
  •  别那么骄傲
    2021-01-18 20:31

    Another non-regex solution:

    function indexesOf(str, word) {
       const split = str.split(word)
       let pointer = 0
       let indexes = []
    
       for(let part of split) {
          pointer += part.length
          indexes.push(pointer)
          pointer += word.length
       }
    
       indexes.pop()
    
       return indexes
    }
    
    console.log(indexesOf('Testing JavaScript, JavaScript is the Best, JavaScript is Ultimate', 'JavaScript'))

提交回复
热议问题