| I, replace method The function of this method is to replace all the specified characters in the string and then generate a new string. After the method call, the original string does not change. For example:
String s = "Abcat"; String S1 = s.replace (' A ', ' 1 '); |
The purpose of this code is to replace all character A in string s with character 1, and the resulting new string S1 value is "1bc1t", while the contents of the string s do not change. If you need to replace a specified string in a string with a different string, you can use the ReplaceAll method, for example:
String s = "Abatbac"; String S1 = s.replaceall ("ba", "12"); |
The purpose of this code is to replace all the string "AB" in the string s with "12", to generate a new string "a12t12c", and the contents of the string s will not change. If you only need to replace the first occurrence of the specified string, you can use the Replacefirst method, for example:
String s = "Abatbac"; String S1 = S. Replacefirst ("Ba", "12"); |
The purpose of this code is to replace only the string "," which appears globally in the string s, with the string "/".
var str = "Is,is,the,cost,of,of,gasoline,going,up,up"; document.write (Str.replace (/\,/g, '/')); |
Use the regular global match to replace the global "," with "/". Example 1 In this example, we will replace "Microsoft" in the string with "jb51.net": ?
| 1234 |
<script type="text/javascript">varstr="Visit Microsoft!"document.write(str.replace(/Microsoft/, "jb51.net"))</script> |
Output: Visit jb51.net! Example 2 In this example, we will perform a global substitution, and whenever "Microsoft" is found, it is replaced with "jb51.net": ?
| 123456 |
<script type="text/javascript">varstr="Welcome to Microsoft! "str=str + "We are proud to announce that Microsoft has "str=str + "one of the largest Web Developers sites in the world."document.write(str.replace(/Microsoft/g, "jb51.net"))</script> |
Output: Welcome to jb51.net! We is proud to announce that Jb51.net Have 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: ?
| 12 |
text = "javascript Tutorial";text.replace(/javascript/i, "JavaScript"); |
Example 4 In this example, we will convert "Doe, John" to the form of "John Doe": ?
| 12 |
name = "Doe, John";name.replace(/(\w+)\s*, \s*(\w+)/, "$2 $1"); |
Example 5 In this example, we'll replace all the curly quotes with straight quotes: ?
| 12 |
name = ‘"a", "b"‘;name.replace(/"([^"]*)"/g, "‘$1‘"); |
Example 6 In this example, we will convert all of the words in the string to uppercase in the first letter: ?
| 1234 |
name = ‘aaa bbb ccc‘;uw=name.replace(/\b\w+\b/g, function(word){ returnword.substring(0,1).toUpperCase()+word.substring(1);} ); |
|