Movatterモバイル変換


[0]ホーム

URL:


  1. Web
  2. JavaScript
  3. Reference
  4. Standard built-in objects
  5. String
  6. search()

String.prototype.search()

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨July 2015⁩.

Thesearch() method ofString values executes a search for a match between a regular expression and this string, returning the index of the first match in the string.

Try it

const paragraph = "I think Ruth's dog is cuter than your dog!";// Anything not a word character, whitespace or apostropheconst regex = /[^\w\s']/g;console.log(paragraph.search(regex));// Expected output: 41console.log(paragraph[paragraph.search(regex)]);// Expected output: "!"

Syntax

js
search(regexp)

Parameters

regexp

A regular expression object, or any object that has aSymbol.search method.

Ifregexp is not aRegExp object and does not have aSymbol.search method, it is implicitly converted to aRegExp by usingnew RegExp(regexp).

Return value

The index of the first match between the regular expression and the given string, or-1 if no match was found.

Description

The implementation ofString.prototype.search() doesn't do much other than calling theSymbol.search method of the argument with the string as the first parameter. The actual implementation comes fromRegExp.prototype[Symbol.search]().

Theg flag ofregexp has no effect on thesearch() result, and the search always happens as if the regex'slastIndex is 0. For more information on the behavior ofsearch(), seeRegExp.prototype[Symbol.search]().

When you want to know whether a pattern is found, andalso know its index within a string, usesearch().

Examples

Using search()

The following example searches a string with two different regex objects to show a successful search (positive value) vs. an unsuccessful search (-1).

js
const str = "hey JudE";const re = /[A-Z]/;const reDot = /[.]/;console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J"console.log(str.search(reDot)); // returns -1 cannot find '.' dot punctuation

Specifications

Specification
ECMAScript® 2026 Language Specification
# sec-string.prototype.search

Browser compatibility

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp