JavaScript replace method
The replace method is used to replace some strings in a string, or replace a string that matches the regular match, and return the replaced string. The syntax is as follows:
The code copy is as follows:
str_object.replace(reg_exp/str, replacement)
Parameter description:
| parameter | illustrate |
|---|---|
| str_object | String (object) to operate |
| reg_exp/str | Required. Regular expression to match/string to replace If reg_exp has the global flag g, the replace() method replaces all matching substrings. Otherwise, it only replaces the first matching substring. |
| replacement | Required. String to replace |
String replacement instance
The following example demonstrates a string replacement instance of the replace method:
The code copy is as follows:
<script language="JavaScript">
var str = "www.example.net";
document.write( str.replace("example", "jb51") );
</script>
Run this example and output:
The code copy is as follows:
www.VeVB.COM
Note: String replacement only replaces the first string that meets the requirements (only replaces once). If you want to replace all strings that meet the requirements in the string, it is recommended to use a regular expression with a global parameter g. See the example below for details.
Regular expression string replacement instance
In addition to supporting simple string replacement, the replace method also supports regular expression replacement:
The code copy is 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 this example and output:
The code copy is as follows:
www.VeVB.COM is a example domains site of INNA.
When adding the global flag g to the regular expression:
The code copy is 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 this example and output:
The code copy is as follows:
www.VeVB.COM is a 5idev domains site of INNA.
Note that if you want to ignore case, you can add the i parameter: /example/gi .