JS: String.prototype.search

By Xah Lee. Date: . Last updated: .

Return the index of first char of matched string. If no match, returns -1.

If the argument is a string, it is converted to a RegExp object.

[see JS: RegExp Object]

const xx = "joe@example.com";

console.log(xx.search(/@.+com/)); // 4

console.log(xx.search(/z/)); // -1
// not found

Here's typical use of “search” method in a “if” statement.

const txt = "dog1051cat";

// check contain digits
const result = txt.search(/\d+/);

if ( result !== -1) {
    console.log("found match");
    console.log(result); // 3
} else {
    console.log("not found");

JS RegExp

  1. RegExp Tutorial
  2. RegExp Syntax
  3. Regex Find/Replace

JS String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence

Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials