You have two possibilites:
(new RegExp('word')).test(str) // or /word/.test(str)
str.indexOf('word') !== -1
Regular expressions seem to be faster (at least in Chrome 10).
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.
Just to save people from running the tests themselves, here are the current results for most common browsers, the percentages indicate performance increase over the next fastest result (which varies between browsers):
Chrome: indexOf (~98% faster)
Firefox: cached RegExp (~18% faster)
IE11: cached RegExp(~10% faster)
Edge: indexOf (~18% faster)
Safari: cached RegExp(~0.4% faster)
Note that cached RegExp is:
var r = new RegExp('simple'); var c = r.test(str); as opposed to:
Does this work for you?
string1.indexOf(string2) >= 0
Edit: This may not be faster than a RegExp if the string2 contains repeated patterns. On some browsers, indexOf may be much slower than RegExp. See comments.
Edit 2: RegExp may be faster than indexOf when the strings are very long and/or contain repeated patterns. See comments and @Felix's answer.
var string = "hello", substring = "lo"; string.includes(substring);
var string = "hello", substring = "lo"; string.indexOf(substring) !== -1;
In ES6, the
includes() method is used to determine whether one string may be found within another string, returning
false as appropriate.
var str = 'To be, or not to be, that is the question.'; console.log(str.includes('To be')); // true console.log(str.includes('question')); // true console.log(str.includes('nonexistent')); // false
Here is jsperf between
var ret = str.includes('one');
var ret = (str.indexOf('one') !== -1);
As the result shown in jsperf, it seems both of them perform well.
For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.
I made a jsben.ch for you http://jsben.ch/#/aWxtF ...seems that indexOf is a bit faster.
It's easy way to use
.match() method to string.
var re = /(AND|OR|MAYBE)/; var str = "IT'S MAYBE BETTER WAY TO USE .MATCH() METHOD TO STRING"; console.log('Do we found something?', Boolean(str.match(re)));
Wish you a nice day, sir!
I've found that using a simple for loop, iterating over all elements in the string and comparing using
charAt performs faster than
Regex. The code and proof is available at JSPerf.
charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com
©2020 All rights reserved.