JavaScript string object replace method instance (for string replacement or regular replacement)
- 2020-03-30 04:06:31
- OfStack
JavaScript is the replace method
The replace method is used to replace one string with another, or to replace a string that matches a regular match, and return the replaced string. The syntax is as follows:
str_object.replace(reg_exp/str, replacement)
Parameter description:
parameter | instructions |
---|---|
str_object | String (object) to manipulate |
reg_exp/str | A necessity. The regular expression to match / The string to replace if reg_exp Global flag g , then replace() Method replaces all matched substrings. Otherwise, it simply replaces the first matched substring. |
replacement | A necessity. The string to replace |
String replacement instance
The following example illustrates a string replacement instance of the replace method:
<script language="JavaScript">
var str = "www.example.net";
document.write( str.replace("example", "jb51") );
</script>
Run the example and output:
www.jb51.net
Note: string substitution replaces only the first string that meets the requirements (only once). If you want to replace all strings that meet the requirements, it is recommended to use the regular expression with the global parameter g pattern, as shown in the following example.
The regular expression string replaces the instance
Run the example and output:
www.jb51.net is a example domains site of INNA.
When adding the global flag g to a regular expression:
<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:
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.