Fastest Way to Check a String Contain Another Substring in JavaScript

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

You have three possibilites:

  1. Regular expression:

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

     str.indexOf('word') !== -1
  3. includes:

     str.includes('word')

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

Performance test - short haystack

Performance test - long haystack


**Update 2011:**

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.


Update 2018:

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) <-- wow
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: /simple/.test(str)

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

const string = "foo";
const substring = "oo";

console.log(string.includes(substring)); // true

What is the fastest way to find which of the substrings is present in a string in javascript?

This seems to be more like a searching problem. Obviously, while searching you do need to make a comparison to match your search term. For this w.r.t. your problem, in JavaScript you can think of Regex and indexOf. But to make it faster for better time complexity you'll have to think of some better search algorithm (Binary Search may be) than a linear iteration over array.

What solution performs faster for searching substring in JavaScript?

indexOf is faster, but you could have easily run these test yourself.

In the future you can use the pattern below to measure execution time:

var str1 = "nananananaananana Catman!";var str2 = "Catman!";var max = 10000000;var t = new Date();for(var i = 0; i < max; i++) {  str1.indexOf(str2) >= 0;}console.log("indexOf",new Date() - t);t = new Date();for(var i = 0; i < max; i++) {  str1.includes(str2);}console.log("includes",new Date() - t);t = new Date();for(var i = 0; i < max; i++) {  str1.indexOf(str2) >= 0;}console.log("indexOf",new Date() - t);t = new Date();for(var i = 0; i < max; i++) {  str1.includes(str2);}console.log("includes",new Date() - t);

How do I check if string contains substring?

Like this:

if (str.indexOf("Yes") >= 0)

...or you can use the tilde operator:

if (~str.indexOf("Yes"))

This works because indexOf() returns -1 if the string wasn't found at all.

Note that this is case-sensitive.

If you want a case-insensitive search, you can write

if (str.toLowerCase().indexOf("yes") >= 0)

Or:

if (/yes/i.test(str))

The latter is a regular expression or regex.

Regex breakdown:

  • / indicates this is a regex
  • yes means that the regex will find those exact characters in that exact order
  • / ends the regex
  • i sets the regex as case-insensitive
  • .test(str) determines if the regular expression matches str
    To sum it up, it means it will see if it can find the letters y, e, and s in that exact order, case-insensitively, in the variable str

How to check if a string contains text from an array of substrings in JavaScript?

There's nothing built-in that will do that for you, you'll have to write a function for it, although it can be just a callback to the some array method.

Two approaches for you:

  • Array some method
  • Regular expression

Array some

The array some method (added in ES5) makes this quite straightforward:

if (substrings.some(function(v) { return str.indexOf(v) >= 0; })) {
// There's at least one
}

Even better with an arrow function and the newish includes method (both ES2015+):

if (substrings.some(v => str.includes(v))) {
// There's at least one
}

Live Example:

const substrings = ["one", "two", "three"];
let str;

// Setup
console.log(`Substrings: ${substrings}`);

// Try it where we expect a match
str = "this has one";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}

// Try it where we DON'T expect a match
str = "this doesn't have any";
if (substrings.some(v => str.includes(v))) {
console.log(`Match using "${str}"`);
} else {
console.log(`No match using "${str}"`);
}

What is the fastest way to check if a string contains only white spaces in JavaScript?

Regular expressions are compiled into a finite state automaton which (for truly regular expressions, like yours) are pretty well optimized and guarantee a linear complexity.

The compilation can take time, which would explain your initial longer time. Any subsequent use of the regex won't need to do that again.

trim is probably also well optimized. It makes sense that both would have similar performance. The third option is clearly more complex.

How to tell if a string contains a certain character in JavaScript?

To find "hello" in your_string

if (your_string.indexOf('hello') > -1)
{
alert("hello found inside your_string");
}

For the alpha numeric you can use a regular expression:

http://www.regular-expressions.info/javascript.html

Alpha Numeric Regular Expression



Related Topics



Leave a reply



Submit