JavaScript
JavaScript

1. String indexOf()

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

var haystack = "foo", needle = "oo";
haystack.indexOf(needle) !== -1; //Output: true

2. String includes()

Starting from ES6, includes() determines whether one string may be found within another string, returning true or false as appropriate.

var haystack = "foo", needle = "oo";
haystack.includes(needle); //Output: true

3. Regex test()

var haystack = "foo",
expr = /oo/; // quotes not needed
expr.test(haystack); //Output: true

If it comes to a point where speed matters. indexOf() might be the best choice

Last modified: January 11, 2018

Author