Skip to content

Instantly share code, notes, and snippets.

@kfiil
Last active May 4, 2017 05:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kfiil/d6855932661bb3aba9d2 to your computer and use it in GitHub Desktop.
Save kfiil/d6855932661bb3aba9d2 to your computer and use it in GitHub Desktop.
Check whether a string contains a substring in #JavaScript.

List of current possibilities:

1. indexOf - (see bottom)

    var string = "foo", 
        substring = "oo"; 
    alert(string.indexOf(substring) > -1);

2. (ES6) includes - go to answer, or this answer

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

3. search - go to answer

    var string = "foo", 
        expr = "/oo/"; 
    string.search(expr);

4. lodash includes - go to answer

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

5. RegExp - go to answer

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

6. Match - go to answer

    var string = "foo", 
        expr = "/oo/"; 
    string.match(expr);

Performance tests (http://jsben.ch/#/RVYk7) are showing that indexOf might be the best choice, if it comes to a point where speed matters.

Source & credits

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