The search() method scans a string for a specified string or regular expression and yields the position of the match.
Example
let text = “Please locate where ‘locate’ occurs!”; text.search(“locate”); |
let text = “Please locate where ‘locate’ occurs!”; text.search(/locate/); |
Are the two methods, indexOf() and search(), equivalent?
Do they accept the same arguments (parameters) and return the same value?
While indexOf() and search() methods share some similarities, they are not identical. Here are the differences:
let text = “The rain in SPAIN stays mainly in the plain”; text.match(“ain”); |
Execute a search for “ain”.
let text = “The rain in SPAIN stays mainly in the plain”; text.match(/ain/); |
Execute a global search for “ain”.
let text = “The rain in SPAIN stays mainly in the plain”; text.match(/ain/g); |
Conduct a case-insensitive global search for “ain”.
let text = “The rain in SPAIN stays mainly in the plain”; text.match(/ain/gi); |
Note If a regular expression lacks the g modifier (indicating a global search), match() will solely return the first match found in the string. |