Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nepsilon/0beb4af175f930432d4ea37f8a4a27f1 to your computer and use it in GitHub Desktop.
Save nepsilon/0beb4af175f930432d4ea37f8a4a27f1 to your computer and use it in GitHub Desktop.
5 ways to check if a string contains a substring in Javascript — First published in fullweb.io issue #89

5 ways to check if a string contains a substring in Javascript

1. ES6 .includes():

var S = "fullweb";
S.includes("web");

2. RegExp .search():

var S = "fullweb";
S.search(/web/);

3. RegExp .match():

var S = "fullweb";
S.match(/web/);

4. RegExp .test():

var S = "fullweb";
S.test(/web/);

5. Good old’ .indexOf():

var S = "fullweb";
S.indexOf("web");

I’ve tested them for speed in Chrome on a MacBook Pro, and it appears ES6 .includes() is the fastest, and .match() is the slowest, with all the others almost as fast as ES6 .includes().

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment