Skip to content

Instantly share code, notes, and snippets.

@Mottie
Created November 1, 2011 00:32
Show Gist options
  • Save Mottie/1329506 to your computer and use it in GitHub Desktop.
Save Mottie/1329506 to your computer and use it in GitHub Desktop.
String.allIndexOf() & Array.allIndexOf()
(function(){
/*
String.allIndexOf(searchstring, ignoreCase)
String [String] - the string to search within for the searchstring
searchstring [String] - the desired string with which to find starting indexes
ignoreCase [Boolean] - set to true to make both the string and searchstring case insensitive
Use:
var s = "The rain in Spain stays mainly in the plain";
s.allIndexOf("ain"); // result [ 5,14,25,40 ]
s.allIndexOf("the"); // result [ 34 ]
s.allIndexOf("THE", true); // result [ 0,34 ]
Demo:
http://wowmotty.blogspot.com/2011/10/get-all-indexof-search-string.html
*/
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]; } // "".indexOf("") is 0
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;
}
/*
Array.allIndexOf(searchElement)
Array [Array] - the array to search within for the searchElement
searchElement [String] - the desired element with which to find starting indexes
Use:
var s = ["red","green","blue","red","yellow","blue","green","purple","red"];
s.allIndexOf("orange"); // result [ -1 ]
s.allIndexOf("red"); // result [ 0,3,8 ]
s.allIndexOf("blue"); // result [ 2,5 ]
Demo:
http://wowmotty.blogspot.com/2011/10/get-all-indexof-from-array.html
*/
Array.prototype.allIndexOf = function(searchElement) {
if (this === null) { return [-1]; }
var len = this.length,
hasIndexOf = Array.prototype.indexOf, // you know, because of IE
i = (hasIndexOf) ? this.indexOf(searchElement) : 0,
n,
indx = 0,
result = [];
if (len === 0 || i === -1) { return [-1]; }
if (hasIndexOf) {
// Array.indexOf does exist
for (n = 0; n <= len; n++) {
i = this.indexOf(searchElement, indx);
if (i !== -1) {
indx = i + 1;
result.push(i);
} else {
return result;
}
}
return result;
} else {
// Array.indexOf doesn't exist
for (n = 0; n <= len; n++) {
if (this[n] === searchElement) {
result.push(n);
}
}
return (result.length > 0) ? result : [-1];
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment