What is the best way to check if one string contains another in JavaScript?

January 04, 2020 No comments QA JavaScript Contains

1. Introduction

There are several methods to check if one string contains another in JavaScript. We listed here some of them, if you know more, please feel free do write that in comments.

2. indexOf method

The indexOf() method returns index of the first occurrence of searched string. If the value is not found it will return -1.

'Test string'.indexOf('Test');     // returns  0
'Test string'.indexOf('Tests');    // returns -1

Keep in mind that indexOf() method is case sensitive.

'Test string'.indexOf('test');     // returns -1
'Test string'.indexOf('String');   // returns -1

It also has second parameter representing the index at which to start the search.

'Test string'.indexOf('st', 0);    // returns 2
'Test string'.indexOf('st', 3);    // returns 5

3. search method

The search() returns the position of the match, or -1 if no match is found. The search value can be string or a regular expression.

'Test string'.search('string');    // returns 5
'Test string'.search(/string/i);   // returns 5

4. match method

The match() method accepts regular expressions only and will return Array with input property if original string match given parameter.

'Test string'.match('Test string'); // ["test", index: 0, input: "test"]
'Test string'.match('aaaaa');       // null

var a = 'Test';
if (a.match(/Test/i)) { 
    // do somethind

5. RegExp method

With regular expressions in JavaScript you have two options to check if one string contains another:

  • test() - method executes a search for a match between a regular expression and a specified string. Returns true or false,
  • exec() - this method search for a match in a specified string. Returns a result array, or null if no match found.

As you can see those methods are very similar but their differ in return type.

// This simple example tests if "Test" is contained at the beginning of the given string. 

var str = 'Test string!';
var result = /^Test/.test(str);
console.log(result); // true
// This example use exec method to check if 'Test string!' contains 'Test' string. It will return Array if exec found a match and null if not.

var matches = /(Test \S+)/.exec('Test string!');
console.log(matches[1]); // Test string!

console.log(matches); // ["Test string!", "Test string!", index: 0, input: "Test string!"]

6. Conclusion

In this article we showcased several methods to check if one string contains another in JavaScript. Is up to you which method you will choose.

{{ message }}

{{ 'Comments are closed.' | trans }}