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 contains another substring (I just need the boolean value)? Could you please suggest your idea and sample snippet code?
This question is related to
javascript
regex
substring
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.
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.
In ES6, the includes()
method is used to determine whether one string may be found within another string, returning true
or 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');
And
var ret = (str.indexOf('one') !== -1);
As the result shown in jsperf, it seems both of them perform well.
I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt
performs faster than indexOf
or Regex
. The code and proof is available at JSPerf.
ETA: indexOf
and charAt
both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com
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!
The Fastest
var string = "hello", substring = "lo"; string.includes(substring);
var string = "hello", substring = "lo"; string.indexOf(substring) !== -1;
Source: Stackoverflow.com