Home >Web Front-end >JS Tutorial >Usage examples of replace() method in Javascript
In our daily development, the replace method in javascript belongs to the String object and can be used to replace strings. Replace can also be used in regular expressions, so today we will discuss in detail the use examples of the replace() method in Javascript!
About the definition
The replace() method is used to replace some characters with other characters in a string, or to replace a substring that matches a regular expression.
About syntax
stringObject.replace(regexp/substr,replacement)
About parameters
##Parameters | Description |
##regexp/substr
|
Required. A RegExp object that specifies the substring or pattern to be replaced. Note that if the value is a string, it is retrieved as a literal literal pattern rather than first being converted to a RegExp object.
|
Required. A string value. Specifies functions for replacing text or generating replacement text. |
#1. The first parameter regexp/substr, when using regular expressions, uses the global identifier g, which can replace all matching substrings, otherwise it will only match once.
var str = "aaaaa"; var str1 = str.replace("a", "b"); var str2 = str.replace(/a/g, "b");Running results: str1 -> "baaaa", str2 -> "bbbbb"2. The second parameter replacement can be a character A string or function, or a specific meaning of the $ character.
$1,$2,...,$99 | |
---|---|
$& | |
$` | |
$' | |
$$ | |
The above is the detailed content of Usage examples of replace() method in Javascript. For more information, please follow other related articles on the PHP Chinese website!