Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gauravmehla/3d0c2378f17ee8a5477b2e19ac03a23a to your computer and use it in GitHub Desktop.
Save gauravmehla/3d0c2378f17ee8a5477b2e19ac03a23a 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