JavaScript String search() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.search() returns the index of the first regular-expression match in a string, or -1 if there is no match (same API as MDN String.prototype.search()). Learn how it differs from indexOf(), test(), and match(), five examples, and try-it labs.

01

Kind

Instance method

02

Returns

Index or -1

03

Input

RegExp (or coerced)

04

g flag

No effect

05

Mutates?

No

06

Baseline

Widely available

Introduction

Need the position of the first regex match — not the matched text itself? search() returns that index, or -1 when nothing matches.

It is the regex-friendly cousin of indexOf(). Use indexOf for literal substrings. Use search when you need patterns such as character classes, flags, or punctuation rules.

💡
Beginner tip

Only need yes/no? Prefer /pat/.test(str).
Need the matched text? Prefer str.match(/pat/).
Need the index of a regex hit? Use str.search(/pat/).

This page is part of JavaScript String Methods. Related topics include indexOf() and match().

Understanding the search() Method

str.search(regexp) runs a regular-expression search against str and returns where the first match starts.

  • Returns a number: match index, or -1 if not found.
  • Non-RegExp values are converted with new RegExp(regexp).
  • The g flag does not change the result.
  • Always searches from the start (lastIndex is treated as 0).
  • Does not return the matched text — only the index.

📝 Syntax

General form of String.prototype.search:

JavaScript
str.search(regexp)

Parameters

  • regexp — a RegExp, or any value with Symbol.search. Other values are coerced via new RegExp(regexp).

Return value

A number:

SituationReturns
Match foundZero-based index of the first match
No match-1
Match at the start0

Common patterns

JavaScript
"hey JudE".search(/[A-Z]/);   // 4  ("J")
"hey JudE".search(/[.]/);    // -1

"ABC".search(/abc/i);        // 0
"hello".search("ell");       // 1  (string → RegExp)

⚡ Quick Reference

GoalCode
Index of first regex matchstr.search(/pat/)
Case-insensitivestr.search(/pat/i)
Literal substring indexstr.indexOf("pat")
Exists? (boolean)/pat/.test(str)
Matched textstr.match(/pat/)

🔍 At a Glance

Four facts to remember about String.search().

Returns
number

Index or -1

Best for
regex index

Not matched text

g flag
ignored

First match only

Mutates
no

Read-only lookup

📋 search() vs indexOf() vs test() vs match()

search()indexOf()test()match()
ReturnsIndex / -1Index / -1true / falseArray / null
PatternRegExpLiteral stringRegExpRegExp / string
Best forWhere is the regex hit?Where is this text?Does it match?What matched?

Examples Gallery

Examples follow MDN String.search() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Find punctuation and capital letters with regex.

Example 1 — Basic search()

MDN demo: find the first character that is not a word, space, or apostrophe.

JavaScript
const paragraph = "I think Ruth's dog is cuter than your dog!";

// Anything not a word character, whitespace, or apostrophe
const regex = /[^\w\s']/g;

const index = paragraph.search(regex);
index;                         // 41
paragraph[index];              // "!"
Try It Yourself

How It Works

The character class skips letters, digits, underscores, spaces, and apostrophes. The first remaining character is the trailing "!" at index 41. The g flag does not change this.

Example 2 — Found vs Not Found

MDN demo: a successful capital-letter search vs a missing dot.

JavaScript
const str = "hey JudE";
const re = /[A-Z]/;
const reDot = /[.]/;

str.search(re);     // 4  (index of "J")
str.search(reDot);  // -1 (no "." in the string)
Try It Yourself

How It Works

/[A-Z]/ finds the first uppercase letter ("J" at index 4). /[.]/ looks for a literal period and returns -1 when none exists.

📈 Practical Patterns

Flags, string coercion, and choosing the right API.

Example 3 — Case-Insensitive Search

Use the i flag when letter case should not matter.

JavaScript
"ABC".search(/abc/);    // -1
"ABC".search(/abc/i);   // 0

"Hello World".search(/world/i);  // 6
Try It Yourself

How It Works

Without i, /abc/ does not match "ABC". With i, the match starts at index 0.

Example 4 — Passing a String

Strings are turned into regular expressions automatically.

JavaScript
"hello world".search("world");  // 6
"file.txt".search(".");         // 0  ( "." means “any char” in regex!)

// Safer for a literal dot:
"file.txt".search(/[.]/);       // 4
"file.txt".indexOf(".");        // 4
Try It Yourself

How It Works

search(".") becomes /./, which matches the first character. For literal punctuation, prefer an escaped regex or indexOf().

Example 5 — Pick the Right Tool

Same sentence, three different questions.

JavaScript
const text = "Order #A42 shipped";

text.search(/#\w+/);          // 6   (where is the code?)
/#\w+/.test(text);            // true (does a code exist?)
text.match(/#\w+/);           // ["#A42"] (what is the code?)
text.indexOf("shipped");      // 11  (literal word position)
Try It Yourself

How It Works

Choose the API that matches the answer you need: index, boolean, matched text, or literal substring position.

🚀 Common Use Cases

  • Find pattern position — locate the first digit, email-like token, or punctuation.
  • Validate then slice — use the index to cut from a match onward.
  • Case-insensitive locatesearch(/word/i) without lowercasing the whole string.
  • Not for literals only — prefer indexOf / includes for plain text.
  • Not for match content — use match / exec when you need the text.
  • Not for every match — use matchAll when you need all hits.

🧠 How search() Finds the Index

1

Normalize the pattern

If needed, coerce the argument to a RegExp.

Input
2

Scan from the start

Look for the first match (g / lastIndex do not change this).

Search
3

Found?

Remember the starting index of that first match.

Decide
4

Return index or -1

A number ready for slicing, checks, or further parsing.

📝 Notes

  • search() returns an index, not the matched text.
  • The g flag has no effect on the result.
  • Strings are coerced to regexes — watch out for metacharacters like ..
  • Prefer indexOf() for literal substrings.
  • Prefer test() for simple yes/no checks.
  • Prefer match() / matchAll() when you need the matched content.

Browser & Runtime Support

String.prototype.search() is Baseline Widely available — supported across modern browsers since July 2015 (and far earlier as a core language feature).

Baseline · Widely available

String.search()

Safe for production in browsers and runtimes (Node.js, Deno, Bun). Use it when you need the index of a regex match.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
search() Excellent

Bottom line: Use String.search() to get the index of the first regex match. Remember -1 means not found, and the g flag does not change the result.

Conclusion

String.prototype.search() answers one clear question: “Where does this regex first match?” Reach for it when you need an index from a pattern, and switch to indexOf, test, or match when your question is different.

Continue with indexOf(), match(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use search() for the index of a regex match
  • Check for -1 before using the index
  • Use the i flag when case should not matter
  • Prefer indexOf for plain literal text
  • Use match when you need the matched string

❌ Don’t

  • Expect g to return every match index
  • Pass "." as a string when you mean a literal dot
  • Use search only to get a boolean — use test
  • Forget that string arguments become regexes
  • Assume a miss returns null — it returns -1

Key Takeaways

Knowledge Unlocked

Five things to remember about String.search()

Get the index of the first regex match.

5
Core concepts
🔎 02

Input

RegExp

Pattern
🎯 03

g flag

no effect

Rule
04

vs indexOf

regex vs literal

Compare
📄 05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.search(regexp) returns the index of the first match of a regular expression in the string, or -1 if nothing matches.
No. The global flag has no effect on search(). It always finds the first match as if lastIndex were 0.
Yes. Non-RegExp values are converted with new RegExp(regexp), so search("cat") behaves like searching with /cat/. Special regex characters in the string still have regex meaning.
Use indexOf() for a literal substring. Use search() when you need a regular expression pattern (character classes, case flags, word boundaries, and so on).
Use test() for a true/false answer. Use search() when you need the match index. Use match() or exec() when you need the matched text or capture groups.
No. Strings are immutable. search() only returns a number (index or -1).
Did you know?

search() mostly delegates to RegExp.prototype[Symbol.search]. That is why custom objects can implement their own search behavior — and why the g flag is ignored for the usual index result.

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful