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

后端 未结 6 451
轮回少年
轮回少年 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'))

    0 讨论(0)
  • 2021-01-18 20:33

    You could use / abuse the replace function:

    var result = [];
    "abcdab".replace(/(a)/g, function (a, b, index) {
        result.push(index);
    }); 
    result; // [0, 4]
    

    The arguments to the function are as follows:

    function replacer(match, p1, p2, p3, offset, string) {
      // p1 is nondigits, p2 digits, and p3 non-alphanumerics
      return [p1, p2, p3].join(' - ');
    }
    var newString = 'abc12345#$*%'.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
    console.log(newString);  // abc - 12345 - #$*%
    
    0 讨论(0)
  • 2021-01-18 20:33

    If you only want to find simple characters, or character sequences, you can use indexOf [MDN]:

    var haystack = "abcdab",
        needle = "a"
        index = -1,
        result = [];
    
    while((index = haystack.indexOf(needle, index + 1)) > -1) {
        result.push(index);
    }
    
    0 讨论(0)
  • 2021-01-18 20:38

    A non-regex variety:

    var str = "abcdabcdabcd",
        char = 'a',
        curr = 0,
        positions = [];
    
    while (str.length > curr) {
        if (str[curr] == char) {
            positions.push(curr);
        }
        curr++;
    }
    
    console.log(positions);
    

    http://jsfiddle.net/userdude/HUm8d/

    0 讨论(0)
  • 2021-01-18 20:43

    You can use the RegExp#exec method several times:

    var regex = /a/g;
    var str = "abcdab";
    
    var result = [];
    var match;
    while (match = regex.exec(str))
       result.push(match.index);
    
    alert(result);  // => [0, 4]
    

    Helper function:

    function getMatchIndices(regex, str) {
       var result = [];
       var match;
       regex = new RegExp(regex);
       while (match = regex.exec(str))
          result.push(match.index);
       return result;
    }
    
    alert(getMatchIndices(/a/g, "abcdab"));
    
    0 讨论(0)
  • 2021-01-18 20:49

    You can get all match indexes like this:

    var str = "abcdab";
    var re = /a/g;
    var matches;
    var indexes = [];
    while (matches = re.exec(str)) {
        indexes.push(matches.index);
    }
    // indexes here contains all the matching index values
    

    Working demo here: http://jsfiddle.net/jfriend00/r6JTJ/

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