Regular expressions in JavaScript (end-of-article)

Source: Internet
Author: User
Tags true true

Regular Expressions in JavaScript (end-of-article)

In previous articles, we learned about the basic syntax of regular expressions, but those grammars are not specific to a particular language. In this blog post we will learn about the use of regular expressions in JavaScript using the following sections:

    • The degree to which JavaScript supports regular expressions
    • RegExp types that support regular expressions
    • Instance properties of RegExp
    • Example method of RegExp
    • RegExp Properties of Constructors
    • Easy to use

 

Part I: The degree to which JavaScript supports regular expressions

Before I introduced the basic syntax of regular expressions, if you do not know very well, you can read the following articles first:

    • The basic concept of regular expressions
    • The digital verification of regular expressions
    • string validation of regular expressions

However, ECMAScript does not support all the functions of the above regular expressions, especially the lack of advanced regular expression features supported by some languages. The following are not supported by javascript:

    • Matches the string start and end of the \a and \z anchors. (But we can still use ^ and $ to match the start and end of the string)
    • Look Backwards (Lookbehind) (note: But JavaScript fully supports forward lookup (lookahead))
    • The set and intersection classes
    • Atomic Group (Atomic grouping)
    • Unicode support (except for single characters, such as \UFFFF)
    • Named capturing group
    • S (single, Row) and X (free-spacing, no interval) matching mode
    • Condition matching
    • Regular expression comments

More about JavaScript support for regular expressions can be clicked here.

Part II: REGEXP types that support regular expressions

JavaScript supports regular expressions through the regexp type. There are two ways to create a regexp type. One is the literal method (similar to Perl's syntax), and the other is the RegExp constructor that uses JavaScript, as described below.

1. Literal methods
var expression =/pattern/flags;

Where expression is the name of the regular expression , the pattern can be any complex or simple regular expression (but must be within the scope of JavaScript support), flags (flags) That is used to indicate the regular expression behavior.

The following is a description of the three flags (flags) supported in javascript:

    1. G: Represents the global mode, which indicates that pattern will be applied to all strings , rather than stopping immediately after a match is found.
    2. I: Indicates case insensitive (ignore) mode . That is, the case of the pattern and the string are ignored.
    3. M: indicates multi-line (multiple) mode. that is, the end of a line of text continues to find out if a matching item exists in the next row.

Description: The flags in the literal method can be any one or a few in G, I, M, and the flags here are fully applicable to the RegExp constructor method to be spoken later.

Example:

var pattern=/at/gi;

The regular expression in this literal form means that the at is matched globally in case insensitive.

2.RegExp constructor Function method
var New REGEXP ("pattern","flags");

This method uses the RegExp constructor and passes two parameters (the same literal method), but it is worth noting that the pattern(pattern) and the flags (flags) need to be enclosed in quotation marks.

  

3. How to escape a meta character in a pattern

When we want to use the meaning of the meta-character itself, we need to escape the metacharacters. For example [ab]c means AC or BC; if escaped by \, \[ab\]c is represented as [Ab]c. However, there are different ways to escape these two different methods of creation.

First, remember that the meta characters in JavaScript have ([{\ ^ $ |)? * +.])}.

Use the literal method to create a regular expression escape: add \ Before the regular expression that needs to be escaped. such as var pattern =/\[ab\]c/g; indicates that the global scope matches the ABC

Use the RegExp constructor to create a regular expression escape: add \ \ Before the regular expression that needs to be escaped. such as var pattern = RegExp ("\\[ab\\]c", "G"), also means matching ABC in global scope

Part III: Instance properties of RegExp

No matter what method you create for regular expressions, they all have the following properties to describe information about the pattern:

    1. The global---Indicates whether the G flag is set in the flags (flags).
    2. The ignoreCase---Indicates whether the I flag is set in the flags (flags).
    3. LastIndex---represents an integer that starts searching for the character position of the next occurrence, starting with 0.
    4. The multiple---Indicates whether the M flag is set in the flags (flags).
    5. The source--- returns the string representation of the regular expression in literal form.

An example is shown below:

// var pattern = RegExp ("\\[ba\\]at", "GI");// The effect created with the RegExp constructor is the same as the method used to create the following literals var pattern =/\[ba\]at/Gi;console.log (pattern. Global // true // trueconsole.log (pattern.multiline);  // tureConsole.log (pattern.lastindex);  //  Console.log (pattern.source);  //   \[ba\]at  

 

Of course, the use of a large number of console.log () in the above code is very complex, you can also pass these 5 properties as 5 parameters directly into Console.log (). As shown below:

var pattern =/\[ba\]at/Gi;console.log (pattern. Global // true True false 0 "\[ba\]at"

 

We can also save these 5 attributes in an array, and then output the array directly through Console.log (), as follows:

var pattern =/\[ba\]at/gi; var properties=[pattern.  Global, Pattern.ignorecase,pattern.multiline,pattern.lastindex,pattern.source];console.log (properties) ;

From the console you can see:

Part IV: an example method of RegExp

Examples of regexp are two methods, exec () and test (), and the ToString () and toLocaleString () methods inherited from object are described below.

EXEC () method for 1.REGEXP instances

This method receives a parameter, the string to which the pattern is to be applied , for capturing the group .

  Returns an array if matching, otherwise null is returned.

And the returned array has an additional two methods: Index and input. Index represents the position of the match in the string, and input represents the string that applies the regular expression.

  An example is shown below:

    var text="mom and Dad and baby";     var pattern=/mom (and Dad (and baby)?)? /gi;     var matches=pattern.exec (text);    Console.log (matches);

If it does not match, then matches is null, and if matched, an array is output in the console, as shown below:

We can see that the array contains three elements, namely Matches[0], matches[1], and matches[2]. And there is an index property of 0 in the array, indicating that the match is positioned in the string at 0, which is the match at the beginning. The input property is the text string.

Test () method for 2.REGEXP instances

This method also receives a string that returns true if pattern (pattern) matches the string, otherwise false.

and the test () method is often used in an if statement, for example, as follows:

<! DOCTYPE html>"en">"UTF-8"> <title>regular expression</title>"text"Id="PhoneNumber"> <button id="Submit"> Submit </button> <script>window.onload=function () {varBtn=document.getelementbyid ("Submit"); Btn.onclick=function () {varPhonenumber=document.getelementbyid ("PhoneNumber"). Value; varpattern=/1[358]\d{9}/gi; if(Pattern.test (PhoneNumber)) {alert ("yes! Your PhoneNumber is legal"); }Else{alert ("no! Your PhoneNumber is illegal"); }        }    }    </script></body>

This small demo can determine whether the user entered the mobile phone number is legitimate, and give a response to the prompt, the demo is as follows:

ToString () and Tolocalstring () methods for 3.REGEXP instances

  Both methods return the literal of the regular expression , regardless of how the regular expression was created.

Examples are as follows:

    var pattern=/1[358]\d{9}/gi;    Console.log (Pattern.tostring ());    Console.log (Pattern.tolocalestring ());

In the console we can see the effect as follows:

Part V:RegExp Constructor Properties

  The RegExp constructor also contains some properties. It is worth noting that these properties have two ways to access---long property names and short property names. introduced as follows:

    1. Input $_ the last string to match. (Note: The former is a long attribute name, the latter is a short attribute name, the same as below)
    2. Lastmatch $& last match to.
    3. Lastparen $+ The most recent matching capture group.
    4. Leftcontext $ ' Input string before lastmatch text
    5. Rightcontext $ ' Input string after lastmatch text
    6. Multiline $* Boolean value that indicates whether all expressions use multiline mode

Note: Opera does not support the 1236 corresponding four properties above, IE does not support the Multiline property.

An example is shown below:

    vartext="This have been a short summer"; varpattern=/(.) hort/G; if(pattern.test (text)) {console.log (regexp.input);//This have been a short summerConsole.log (Regexp.leftcontext);//This have been aConsole.log (Regexp.rightcontext);//SummerConsole.log (Regexp.lastparen);//sConsole.log (Regexp.lastmatch);// ShortConsole.log (Regexp.multiline);//undefined}

Part VI: A simple application1. User name and password verification

The requirements are as follows:

    1. User name Input: must be the length in the 5~20 between the English letter, otherwise submitted after the error.
    2. Password input: Must be a combination of numbers and letters, and the length must be 8, otherwise submitted after the error.

Implementation ideas:

    1. If the user name and password are correct at the same time, the "success" is displayed correctly.
    2. The user name is wrong, the password is correct, the "user name is wrong, please re-enter ..."
    3. The user name is correct, the password is wrong, then the "password is wrong, please re-enter ..."
    4. User name and password are wrong, the display "User name and password are entered incorrectly!!!" ”

The code looks like this:

<! DOCTYPE html>"en">"UTF-8"> <title>regular expression</title> <style>Input{box-sizing:border-box;padding:10px;width:300px;height:50px;line-height:50px;} Input[type="Submit"]{height:30px;line-height:30px;padding:0;} </style>""> <input type="text"Id="username"Placeholder="Please enter the English name of the length before 5~20 ..."><br> <input type="Password"Id="Password"Placeholder="Please enter a number with a length of 8 and a password in English ..."><br> <input type="Submit"Id="Submit"Value="Submit"> </form> <script>window.onload=function () {varBtn=document.getelementbyid ("Submit"); Btn.onclick=function () {Event. Preventdefault (); varUsername=document.getelementbyid ("username"); varPassword=document.getelementbyid ("Password"); varusernamepattern=/[a-za-z]{5, -}/G; varpasswordpattern=/[\da-za-z]* ((\d+[a-za-z]+) | ( [a-za-z]+\d+)] [\da-za-z]*/G; if(Usernamepattern.test (Username.value) && (Passwordpattern.test (password.value) && ( password.value.length==8)) {alert ("Success! "); }Else if((!usernamepattern.test (Username.value)) && (Passwordpattern.test (password.value) && ( password.value.length==8)) {alert ("user name input is wrong! Please re-enter ..."); }Else if((! (Passwordpattern.test (Password.value) && (password.value.length==8))) &&usernamepattern.test (Username.value)) {Alert ("Wrong Password input! Please re-enter ..."); }Else{alert ("user name and password are entered in error!!! ");    }        }    }; </script></body>

The key is to determine whether the input is accurate or not, and here I am using the operation. If the password is entered correctly, the user name is wrong when the user name of the judgment code to take non- can, other similar.

The effect is as follows:

OK, this blog post is here, if you feel good, recommend it!

Note: Original article, if you want to reprint, please indicate the source. Blog Address: http://www.cnblogs.com/zhuzhenwei918/p/6204445.html

Thousand scouring million, although hard, blowing the sand began to gold.

Regular expressions in JavaScript (end-of-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.