UK[rɪˈpleɪs] US[rɪˈples]
vt.Replace; replace; put... back into its original place; (with...) replace
Third person singular: replaces Present participle: replacing Past tense: replaced Past participle: replaced
javascript replace() method syntax
Function: is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression.
Syntax: stringObject.replace(regexp/substr,replacement)
Parameters: 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 rather than first being converted to a RegExp object. replacement Required. A string value. Specifies functions for replacing text or generating replacement text.
Returns: A new string obtained by replacing the first match or all matches of regexp with replacement.
Description: The replace() method of string stringObject performs a search and replace operation. It will look for substrings in stringObject that match regexp and then replace those substrings with replacement. If the regexp has the global flag g, then the replace() method replaces all matching substrings. Otherwise, it only replaces the first matching substring. replacement can be a string or a function. If it is a string, then each match will be replaced by the string. But the $ character in replacement has a specific meaning. As shown in the following table, it illustrates that the string obtained from the pattern match will be used for replacement.
Note: ECMAScript v3 stipulates that the parameter replacement of the replace() method can be a function instead of a string. In this case, the function is called for each match and the string it returns is used as the replacement text. The first parameter of this function is a string matching the pattern. The next argument is a string that matches the subexpression in the pattern, and there can be 0 or more such arguments. The next parameter is an integer that declares the position in the stringObject where the match occurs. The last parameter is the stringObject itself.
javascript replace() method example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script type="text/javascript"> var str="Visit Microsoft!" document.write(str.replace(/Microsoft/, "php.cn")) </script> </body> </html>
Run instance »
Click the "Run instance" button to view the online instance