regex vs while loops

后端 未结 2 1913
天涯浪人
天涯浪人 2021-01-13 07:01

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

2条回答
  •  爱一瞬间的悲伤
    2021-01-13 07:16

    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.

提交回复
热议问题