JavaScript: String Methods for Regex

By Xah Lee. Date: . Last updated: .

Regex is used for matching text patterns.

There are 2 ways to use regex in JavaScript:

String Methods for Regex

String.prototoype.replace
syntaxdescription
s.replace(find_str,replace_str)Returns a new string. The first occurrence of find_str in string s is replaced by string replace_str. (no regex) If no match, the original string is returned. 〔➤see JavaScript: String.prototoype.replace
s.replace(regex_obj,replace_str_or_func)Return a new string. The replace_str_or_func can be a string or function. If string, {$1, $2, …} refers to captured group. If function, it'll receive args: {matched substring, capture group 1, capture group 2, …}. If no match, the original string is returned. ES5 §15#sec-15.5.4.11 〔➤see JavaScript: String.prototoype.replace
String.prototoype.search
syntaxdescription
s.search(/…/) or s.search("…")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 regex object. ES5 §15#sec-15.5.4.12 〔➤see JavaScript: String.prototoype.search
String.prototoype.match
syntaxdescription
s.match(/…/) or s.match("…")Return a array of captured patterns. Index 0 is the whole matched string, index 1 is first captured pattern, …. Or, return null if no match. If the argument is a string, it is converted to a regex object. ES5 §15#sec-15.5.4.10 〔➤see JavaScript: String.prototoype.match
s.match(/…/g)Return a array of all occurrences of matched string (note the g flag for global), or null if no match. 〔➤see JavaScript: String.prototoype.match

The syntax for regex is /pattern/flags (using slash as delimiter, not quotation symbol). It is a literal expression for regex object.

If a string "pattern" is given as argument:

Regex Object Methods

JavaScript: RegExp Object

Regex Syntax

JavaScript: Regex Syntax

Like what you read? Buy JavaScript in Depth.