In JavaScript, the syntax of the replace method is "String object.replace (string to be replaced, new string)". The replace method is used to replace some characters with other characters in a string. Or replace a substring that matches a regular expression.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Thereplace() method 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)
Return value
A new string obtained by replacing the first match or all matches of regexp with replacement.
Explanation
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.
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.
Example:
<script type="text/javascript"> var str="Visit cmcc!" document.write(str.replace(/cmcc/, "apply")) </script>
Effect:
Visit apply!
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of How to use replace method in javascript. For more information, please follow other related articles on the PHP Chinese website!