Find the index of all occurrences in a jquery string

Asked

Viewed 114 times

3

How to find the index of all occurrences of a 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"

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);
}

Follows the fiddle.


An alternative without regex would be to implement it 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;
  }
})();

Use:

suaString.allIndexOf("três");

Follows the fiddle.

Note: The above alternatives are without jQuery hehe'

  • 1

    Oops, thanks a lot! Helped a lot :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.