Skip to content

Instantly share code, notes, and snippets.

@rd13
Created May 8, 2013 11:19
Show Gist options
  • Save rd13/5539824 to your computer and use it in GitHub Desktop.
Save rd13/5539824 to your computer and use it in GitHub Desktop.
String search functions in Javascript, tests with and without Regex. Summary: Regex is faster. http://jsperf.com/javascript-find-all
// http://jsperf.com/javascript-find-all
function indexes(str, find) {
var result = [];
for(i=0;i<str.length; ++i) {
if (str.substring(i, i + find.length) == find) {
result.push(i);
}
}
return result;
}
console.log(indexes("I learned to play the Ukulele in Lebanon.", "le"));
function indexes2(str, find) {
var regex = new RegExp(find,"g");
var result,
indices = [];
while ( (result = regex.exec(str)) ) {
indices.push(result.index);
}
return indices;
}
console.log(indexes2("I learned to play the Ukulele in Lebanon.", "le"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment