JavaScript Replace method
The Replace method is used to replace some strings in strings, or to replace strings that match a regular match, and to return the replaced string. The syntax is as follows:
Copy Code code as follows:
Str_object.replace (REG_EXP/STR, replacement)
Parameter description:
Parameters |
Description |
Str_object |
The string to manipulate (object) |
Reg_exp/str |
Necessary. The regular expression to match/the string to replace If Reg_exp has global flag G, then the Replace () method replaces all matching substrings. Otherwise, it replaces only the first matching substring. |
Replacement |
Necessary. The string to replace |
String Substitution instance
The following example shows a string substitution instance of the Replace method:
Copy Code code as follows:
<script language= "JavaScript" >
var str = "Www.example.net";
document.write (Str.replace ("Example", "jb51"));
</script>
Run the example and output:
Copy Code code as follows:
Note: string substitution replaces only the first qualifying string (only once), and if you want to replace all strings that match the required string, it is recommended to use a regular expression with global parameter g, as shown in the following example.
The regular expression string replaces an instance
The Replace method supports regular expression substitution in addition to simple string substitution:
Copy Code code as follows:
<script language= "JavaScript" >
var str = "Www.example.net is a example domains site of Inna.";
document.write (Str.replace (/example/, "jb51"));
</script>
Run the example and output:
Copy Code code as follows:
Www.jb51.net is a example domains site of Inna.
When you add a global flag G to a regular expression:
Copy Code code as follows:
<script language= "JavaScript" >
var str = "Www.example.net is a example domains site of Inna.";
document.write (Str.replace (/example/g, "jb51"));
</script>
Run the example and output:
Copy Code code as follows:
Www.jb51.net is a 5idev domains site of Inna.
Note that if you want to ignore case, you can add the I parameter:/example/gi.