Đinh Hồng Châu Đinh Hồng Châu - 1 month ago 5
Javascript Question

Fastest way to check a string contain another substring in Javascript?

I'm working with a performance issue on Javascript. So I just want to ask: what is the fastest way to check whether a string contain another substring (I just need the boolean value)? Could you please suggest your idea and sample snippet code?! Thank you so much!

Answer

You have two possibilites:

  1. Regular expression:

    (new RegExp('word')).test(str)
    // or
    /word/.test(str)
    
  2. indexOf:

    str.indexOf('word') !== -1
    

Regular expressions seem to be faster (at least in Chrome 10).

Performance test - short haystack
Performance test - long haystack

Update:

It cannot be said with certainty which method is faster. The differences between the browsers is enormous. While in Chrome 10 indexOf seems to be faster, in Safari 5, indexOf is clearly slower than any other method.

You have to see and try for your self. It depends on your needs. For example a case-insensitive search is way faster with regular expressions.

Comments