Find the index of all occurrences in a string with jquery

3

How to find the index of all occurrences of a one string within another string with jquery?

Example: String all "three sad tigers for three wheat dishes, three wheat dishes for three sad tigers."

String I want to find the indexes: "three"

    
asked by anonymous 09.03.2016 / 14:29

1 answer

2

You can use a regex combined with a while to do this:

var re = /três/g,
    idx = [],
    str = "três tigres...";

while ((match = re.exec(str)) != null) {
    idx.push(match.index);
}

Follow the fiddle .

Another alternative without regex, would be implemented under the prototype of the String itself. The code is much more extensive:

(function() {
  String.prototype.allIndexOf = function(string, ignoreCase) {
    if (this === null) {
      return [-1];
    }
    var t = (ignoreCase) ? this.toLowerCase() : this,
      s = (ignoreCase) ? string.toString().toLowerCase() : string.toString(),
      i = this.indexOf(s),
      len = this.length,
      n,
      indx = 0,
      result = [];
    if (len === 0 || i === -1) {
      return [i];
    }
    for (n = 0; n <= len; n++) {
      i = t.indexOf(s, indx);
      if (i !== -1) {
        indx = i + 1;
        result.push(i);
      } else {
        return result;
      }
    }
    return result;
  }
})();

Usage:

suaString.allIndexOf("três");

Follow the fiddle .

Note: The above alternatives are without jQuery hehe '

    
09.03.2016 / 17:19