Article transferred from http://www.w3school.com.cn/jsref/jsref_replace.asp
| character |
Replace text |
| $, $ 、...、 |
The text that matches the 1th to 99th sub-expression in RegExp. |
| $& |
A substring that matches the regexp. |
| $` |
The text that is located to the left of the matching substring. |
| $ |
The text on the right side of the matching substring. |
| $$ |
Direct volume symbol. |
Example 1
In this example, we will replace "Microsoft" in the string with "W3school":
<script type= "Text/javascript" >var str= "Visit microsoft!" document.write ( str.replace(/Microsoft/, "W3School") ) </script>
Output:
Visit w3school!
Example 2
In this example, we will perform a global substitution, and whenever "Microsoft" is found, it is replaced with "W3school":
<script type= "Text/javascript" >var str= "Welcome to microsoft! "Str=str +" We are proud to announce that Microsoft have "Str=str +" one of the largest WEB developers sites in the world. " document.write ( str.replace(/Microsoft/g, "W3School") ) </script>
Output:
Welcome to w3school! We is proud to announce this W3schoolhas one of the largest WEB developers sites in the world.
Example 3
You can use the code provided in this example to ensure that the matching string is correct for uppercase characters:
Text = "JavaScript Tutorial"; Text.replace (/javascript/i, "JavaScript");
Example 4
In this example, we will convert "Doe, John" to the form of "John Doe":
Name = "Doe, John"; Name.replace (/(\w+) \s*, \s* (\w+)/, "$ $");
Example 5
In this example, we'll replace all the curly quotes with straight quotes:
name = ' A ', "B" '; Name.replace (/"([^"]*) "/g," ' $ ' ");
Example 6
In this example, we will convert all of the words in the string to uppercase in the first letter:
Name = ' aaa bbb ' CCC '; Uw=name.replace (/\b\w+\b/g, function (word) { return word.substring (0,1). toUpperCase () + Word.substring (1);} );
JavaScript Replace () method