Introduction to the use of replace method in js

  • 2020-03-26 21:43:06
  • OfStack

The replace() method is used to replace a string with some characters for another, or to replace a substring that matches the regular expression.

Note: If the regexp has a global flag g when replaced with a regular expression, the replace() method replaces all matched substrings. Otherwise, it simply replaces the first matched substring.

Here's a simple example:
 
<script language="javascript"> 
var strM = "javascript is a good script language"; 
//Here I want to replace the letter a with the letter a
alert(strM.replace("a","A")); 

</script> 
//As a result, it just replaces the first letter. But if you add a regular expression, the result is different! Replace () supports regular expressions that match characters or strings according to the rules of regular expressions and then give them a replacement!
<script language="javascript"> 
var strM = "javascript is a good script language"; 
//Here I want to replace the letter a with the letter a
alert(strM.replace(/a/,"A")); 
</script> 
//But the result still has not changed, slightly modification is OK.

<script language="javascript"> 
var strM = "javascript is a good script language"; 
//Replace the letter a with the letter a. when the regular expression has a "g" flag, the whole string will be processed
alert(strM.replace(/a/g,"A")); 
</script> 

Related articles: