The usage of replace function in JS regular expression

Time:2020-10-29

Regular expression replace() function:
This function replaces the substring in the string that matches the regular expression with the specified string.
The return value is a new string after replacement.
This article only introduces the regular expression related operations. For other replacement operations, please refer to the article “replace() method of JavaScript string object”.
Grammatical structure:

stringObject.replace(regexp,replacement)

The parameter list is as follows:

Parameter name semantic interpretation
regexp Required. Regexp object.
replacement Required. A string value. Specifies the function to replace text or generate replacement text.

Example code:


<script>
var str="I love jb51";
var reg=/j(?:\w)+1/;
console.log(str.replace(reg,"girls"));
</script>

The above code can replace the substring in the string that can be matched by regular expression with “girls”.

Special instructions:
Replacement can be a string or a function. If it is a string, then each match is replaced by a string.
The $character in replacement can have a specific meaning, as shown in the following table:

character semantic interpretation
$1、$2、…、$9 The text that matches the 1st to 9th subexpressions in regexp.
$& Substring that matches regexp.
$$ Direct quantity symbol.
$` The text before lastmatch in the input string.
$’ The text after lastmatch in the input string.

If replacement is a function, please refer to the section of JavaScript’s replace() where the second parameter is a function parameter.
Example code:


<script>
var str="jb51,net"; 
var newStr=str.replace(/(\w+),(\w+)/,"$2 $1"); 
console.log(newStr);
</script>

Output:net jb51

Function function: the replace function returns the copy of the string after literal replacement according to regular expression.

Function format: stringObj.replace (rgExp, replaceText)

Parameters: String obj, rgexp, regular expression, content replaced by replacetext

The contents of this paper include string creation, regular expression implicitly creating object, creating regular expression, and using replace method to match

Example code:

<html> 
<script language="javascript" type="text/javascript"> 
//The content of the string to replace 
var objStr=new String("Designed By Androidyue"); 
//Implicitly creating regular expression objects 
Var reg = / E / W? / g; // global matching (G is the global matching parameter), matching e or e? content 
Var re = / E / W? /; // no parameter is specified, and the value is matched once 
with(document){ 
Write ("string before matching" + objstr + "< br >"); 
Write ("string with global match"+ objStr.replace (reG,"**")+"<br>"); 
Write ("match, no parameter value specified for one match"+ objStr.replace (re,"××")); 
} 
</script> 
</html>

I’ll write a few articles about regular expressions. Of course, the best way is to try to write something yourself