December 2023
Intermediate to advanced
242 pages
5h 28m
English
The search() method executes a search on a string and returns an integer indicating the index of the first match. If no match is found, the return value will be -1:
| | const str = "Eat well, stay fit, die anyway."; |
| | |
| | // Using a string as the pattern |
| | console.log(str.search("fit")); // → 15 |
| | |
| | // Using a regular expression as the pattern |
| | console.log(str.search(/fit/)); // → 15 |
Unlike exec() or test(), the search() method does not support the global flag and ignores the lastIndex property. This means it always executes a search from the beginning of the string and returns the index of the first match.
Read now
Unlock full access