As expected, regular expressions are also a type of JavaScript object. There are two ways to construct regular expressions, one is to use the new RegExp () constructor built into JavaScript, and the other is to suggest a literal declaration:
Regular expression Literalvar re =/\\/gm;//Constructorvar re = new RegExp ("\\\\", "GM");
It can be seen that the literal declaration method (Literal) is more concise, because it does not have to be quoted, so there is no need to use two \ to represent a slash as a parameter in the constructor.
When you use literal notation to create a regular expression, the letters that follow indicate the following meanings:
- G-Global Match
- M-Multi-line
- I-Case sensitive
The match and pattern (pattern) plus the subsequent set letters make up the literal declaration of the regular expression:
Many of the string's handler functions, such as String.prototype.replace (), accept the literal declaration of the regular expression as a parameter:
var no_letters = "abc123xyz". Replace (/[a-z]/gi, ""); Console.log (no_letters); 123
Another difference between the use of literal declarations and constructors to generate regular expressions is that when the regular expression object is returned by a function, the literal declaration always guarantees that the same object is returned, and the constructor returns an object that has the same content but differs from the individual. Consider the following code:
function Getre () {var re =/[a-z]/;re.foo = "Bar"; return re;} var reg = Getre (), Re2 = Getre (); Console.log (reg = = = Re2); Truereg.foo = "Baz"; Console.log (Re2.foo); "Baz"
If you put var re =/[a-z]/; here for new RegExp (), then console.log (reg = = = = Re2); returns false.
The literal declaration of the JavaScript base regular expression (012)