javascript tutorial - [Solved-5 Solutions] substring in JavaScript - javascript - java script - javascript array
Problem:
How to check whether a string contains a substring in JavaScript?
Solution 1:
indexof()
should actually be
indexOf()
Try fixing it and see if that helps:
if (test.indexOf("title") !=-1) {
alert(elm);
foundLinks++;
}
click below button to copy the code. By JavaScript tutorial team
Solution 2:
var index = haystack.indexOf(needle);
click below button to copy the code. By JavaScript tutorial team
Solution 3:
"potato".includes("to");> true
click below button to copy the code. By JavaScript tutorial team
we may need to load es6-shim or similar to get this working on older browsers.require('es6-shim')
Solution 4:
we could use the JavaScript search()
method.
Syntax is: string.search(regexp)
It returns the position of the match, or -1 if no match is found.
See examples there: jsref_search
We don't need a complicated regular expression syntax. If we are not familiar with them a simple st.search("title")
will do. If we want your test to be case insensitive, then we should do st.search(/title/i)
.
Solution 5:
Determines whether one string may be found within another string, returning true or false as appropriate.
Syntax
var contained = str.includes(searchString [, position]);
click below button to copy the code. By JavaScript tutorial team
Parameters
searchString
A string to be searched for within this string.
position
The position in this string at which to begin searching for searchString defaults to 0.
Example
var str = "To be, or not to be, that is the question.";
console.log(str.includes("To be")); // true
console.log(str.includes("question")); // true
console.log(str.includes("To be", 1)); // false5