Skip to content

Instantly share code, notes, and snippets.

@kheyro
Last active April 11, 2018 09:23
Show Gist options
  • Save kheyro/6bba12989edfb745633d047a2bc40fdd to your computer and use it in GitHub Desktop.
Save kheyro/6bba12989edfb745633d047a2bc40fdd to your computer and use it in GitHub Desktop.
[[JS] String contains a substring?] All the differents ways to find if a string contains a substring

1. ES6 includes - got to answer

let string = "foo",
  substring = "oo";
string.includes(substring);
// true

2. ES5 and older indexOf

let string = "food",
  substring = "d";
string.indexOf(substring); // 3
string.indexOf(substring) !== -1; // true
!!~string.indexOf(substring); // true

3. Search - go to answer

let string = "food",
  expr = /d/;
string.search(expr); // 3

4. lodash includes - go to answer

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

5. RegExp - go to answer

let string = "foo",
  expr = /oo/;  // no quotes here
expr.test(string); // true

6. Match - go to answer

let string = "foo",
  expr = /oo/;
string.match(expr);
// ["oo", index: 1, input: "foo", groups: undefined]

To go further

  • Performance tests are showing that match and includes might be the best choice, if it comes to a point where speed matters.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment