While reading this SO post - Is there a version of JavaScript's String.indexOf() that allows for regular expressions?) I ponder which of the following two functions that
You can use jsPerf to compare the performance of different JavaScript snippets. I’ve created one that uses your two variants and this one by me:
function(str) {
var parts = str.split(/(?=\s+)/);
return parts.length === 1 ? -1 : str.length - parts[parts.length-1].length;
}
It basically splits the string at the position of the match using a look-ahead assertion. If no match is found, split
returns an array with just one item; otherwise the length of the last part is subtracted from the total length of the string to get the index of the last match.
Update I’ve tweaked the functions a little bit and now we’ve got some completely different results compared to the previous benchmark. Now the first function that is now using /\s+(?!\S+\s+)/
instead of /\s+(?!.*\s+)/
seems to be the fastest.