JavaScript String search()

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

search() Syntax and Return Value Top ↑

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.

Search Using Text Top ↑

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.

Search with a Regular Expression Top ↑

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.

When search() Finds No Match Top ↑

const text = "JavaScript";
if (text.search(/python/i) === -1) {
  console.log("Not found");
}

search() vs indexOf() Top ↑

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.

search() vs match() and matchAll() Top ↑

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.

Check Whether a URL Prefix Appears Top ↑

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.

Common search() Mistakes Top ↑

  • Expecting the matching text rather than its index.
  • Forgetting to compare the result with -1.
  • Expecting a second argument to set the starting position.
  • Using an unescaped regular-expression pattern when the search text contains regex metacharacters.
  • Using search() for a plain substring when includes() would be simpler.

String Reference Lowercase Strings




Subscribe to our YouTube Channel here



plus2net.com







Narendran

13-03-2010

Superb



We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
©2000-2026   plus2net.com   All rights reserved worldwide Privacy Policy Disclaimer