Created
May 8, 2013 11:19
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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