The literal declaration of the JavaScript base regular expression (012)

Source: Internet
Author: User

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)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.