Check whether a given string contains a sub-string using JavaScript ?
There can be many ways to solve this problem. Some of the possible ways are given below.
For ES6: includes .
The includes() method determines whether one string may be found within another string, returning true or false as appropriate.
Syntax : str.includes(searchString[, position]) Example:
'Technical knowledge point'.includes('javascript'); // returns false 'Technical knowledge point'.includes('knowledge'); // returns true
For ES5 or below: indexOf .
The indexOf() method returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex. Returns -1 if the value is not found. Syntax: str.indexOf(searchString[, fromIndex])
Example:
'Technical knowledge point'.indexOf('javascript'); // returns -1 'Technical knowledge point'.indexOf('knowledge'); //returns 10
Search
The search() method searches a string for a specified value, and returns the position of the match. The search value can be string or a regular expression. This method returns -1 if no match is found.
Syntax: str.search(searchString)
Example:
'Technical knowledge point'.search('javascript'); // returns -1
'Technical knowledge point'.search('knowledge'); //returns 10
'Technical knowledge point'.search(/T/i); // returns 0
'Technical knowledge point'.search(/k/i); //returns 10
'Technical knowledge point'.search(/p/i); //returns 20