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

Usually I would expect a String.contains() method but there doesn't seem to be one. What is a reasonable way to check for this?

Text Copied From
on : Tue, Nov 24, 2009 Views : 4594956

Accepted Answer

Here is a list of current possibilities:

1. indexOf

var string = foo,
  substring = oo;
 string.indexOf(substring) !== -1;

String.prototype.indexOf returns the position of the string in the other string. If not found, it will return -1.

2. (ES6) includesgo to answer

var string = foo,
  substring = oo;

3. searchgo to answer

var string = foo,
  expr = /oo/;;

4. lodash includesgo to answer

var string = foo,
  substring = oo;
 _.includes(string, substring);

5. RegExpgo to answer

var string = foo,
  expr = /oo/;
// no quotes here expr.test(string);

6. Matchgo to answer

var string = foo,
  expr = /oo/;

Performance tests are showing that indexOf might be the best choice, if it comes to a point where speed matters.

Text Copied From
on : Tue, Nov 24, 2009

Ask Question

If you want to ask question you must LogIn or SignUp
Login SignUp

Quick Links



Total Followers
Study Group Created
Study Group Joined
Following Teacher
Following Organization
Blog Articles Added
Questions Asked
Questions Answered
Jobs Posted
Total Members in Group
Questions asked by members
Tasks added in this Group

Please wait..


Login to Open ESchool OR Create your account    Login   SignUp