Home >Web Front-end >JS Tutorial >How to use javascript replace
javascript replace method is used to replace some characters with other characters in a string or replace a substring that matches a regular expression. Its usage syntax is "stringObject.replace(regexp/substr,replacement)" .
The operating environment of this article: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
javascript replace usage details
#replace() method is used to replace some characters with other characters in a string, or replace a substring that matches a regular expression. string.
Syntax
stringObject.replace(regexp/substr,replacement)
Parameters regexp/substrRequired: 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 text pattern, rather than first being converted to a RegExp object.
replacement Required: a string value. Specifies functions for replacing text or generating replacement text.
Return value: 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 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.
Usage example
在本例中,我们将使用 "W3School" 替换字符串中的 "Microsoft": <script type="text/javascript"> var str="Visit Microsoft!" document.write(str.replace(/Microsoft/, "W3School")) </script>
Output:
Visit W3School!
Recommended study: "javascript basic tutorial"
The above is the detailed content of How to use javascript replace. For more information, please follow other related articles on the PHP Chinese website!