SoFunction
Updated on 2025-03-03

Regular expression matching, replacement, search

The previous article introduced it to youJava regular expression matching, replacement, searching, and cutting methodsNext, I will introduce it to you through this articlejs regular matching, search and replace,For details, please see below.

js regular matching, search and replacement

RegExp Object The RegExp object represents a regular expression, which is a powerful tool for performing pattern matching on strings. Direct quantity syntax/pattern/attributes syntax for creating RegExp objects: newRegExp(pattern, attributes); parameter parameter pattern...

RegExp Object

The RegExp object represents a regular expression, which is a powerful tool for performing pattern matching on strings.

Direct grammar

/pattern/attributes

Syntax for creating RegExp objects:

new RegExp(pattern, attributes);

parameter

The parameter pattern is a string that specifies the pattern or other regular expression of the regular expression.

The parameters attributes are an optional string containing attributes "g", "i" and "m", which are used to specify global matches, case-sensitive matches, and multi-line matches, respectively. The m attribute is not supported until ECMAScript is standardized. If pattern is a regular expression, not a string, the parameter must be omitted.

Return value

A new RegExp object with specified schema and flags. If the parameter pattern is a regular expression instead of a string, the RegExp() constructor creates a new RegExp object with the same pattern and flags as the specified RegExp .

If you don't use the new operator and use RegExp() as a function, it behaves the same as when called with the new operator, except that when pattern is a regular expression, it only returns pattern and no longer creates a new RegExp object.

Throw out

SyntaxError – If pattern is not a legal regular expression, or attributes contains characters other than "g", "i" and "m", throw this exception.

TypeError – If pattern is a RegExp object, but the attributes parameter is not omitted, the exception is thrown.

javascript code

var string = "Hello";
var pattern = "/good/";
((pattern, '<strong>$1</strong>')); // $1 Represents a matching string

javascript code

var string = "Hello";
var pattern = "/good/";
((pattern)); //Return value type: Array [Array]

javascript code

var string = "Hello";
var pattern = "/good/";
((pattern)); //Return value type: Int [Array]