search() returns the index of the first match in a string. Its main strength is regular-expression searching. If no match is found, it returns -1.
const text = "Learn JavaScript";
console.log(text.search(/javascript/i)); // 6
string.search(regexp)
If you pass a non-RegExp value, JavaScript converts it to a regular expression. The method returns the first matching index or -1.
const text = "Welcome to https://www.plus2net.com";
console.log(text.search("https://"));
For a plain literal search, indexOf() or includes() often communicates the intent more directly.
const text = "Order ID: AB-2048";
const position = text.search(/[A-Z]{2}-\d{4}/);
console.log(position);
Flags such as i make a pattern case-insensitive.
const text = "JavaScript";
if (text.search(/python/i) === -1) {
console.log("Not found");
}
Both return the first matching index or -1. indexOf() is designed for literal strings and accepts a starting position. search() is designed around regular expressions and does not provide a start-position argument.
Use search() when you need only the first index. Use match() when you need match data. Use matchAll() with a global regular expression when you need all matches plus capture information.
The original page checked whether https:// exists inside a string. A clearer modern version is:
const value = "Welcome to https://www.plus2net.com";
const position = value.search(/https:\/\//);
if (position === -1) {
console.log("Not found");
} else {
console.log(`Found at index ${position}`);
}
Once text is found, replace() can be used when the next task is substitution.
-1.search() for a plain substring when includes() would be simpler.String Reference Lowercase Strings
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| Narendran | 13-03-2010 |
| Superb | |