Easy Learning JavaScript 14: JavaScript's RegExp object (regular expression)

Source: Internet
Author: User

Overview of a RegExp object

The RegExp object represents a regular expression, and regexp is the abbreviation for a regular expression, which is a powerful tool for performing pattern matching on strings. Regexp

object is used to specify what is retrieved in the text. When you retrieve a text, you can use a pattern to describe what you want to retrieve. RegExp, that's it.

Mode. A simple pattern can be a single character, more complex patterns include more characters, and can be used for parsing, formatting checking, replacing, and so on.

A regular expression can specify the location of the search in a string, as well as the type of character to retrieve.

Two Create Rexexp objects

Similar to creating a regular expression and creating a string, there are two ways to create a regular expression:

(1) The syntax for creating RegExp objects using literals:

/pattern/attributes;

(2) Use the new keyword to create the syntax for the RegExp object:

New REGEXP (pattern, attributes);

Parameter explanation:

1 parameter pattern is a string that specifies the pattern of a regular expression or other regular expression.

2 parameter attributes is an optional pattern string that contains the attribute "G", "I", and "M", respectively, for specifying a globally matched, case-insensitive

Matching with multiple lines.

The RegExp object is used to store the retrieval mode. Create a RegExp object with the New keyword. The following generation creates a regexp that is named pattern

Like, its pattern is "e", when the RegExp object is retrieved in a string, the character "e" is searched.

<span style= "FONT-SIZE:18PX;" >var pattern=new RegExp ("E"); var pattern=new RegExp ("E", GI);//Set global search case insensitive </span>

The above can also be changed into a literal way to create, which is also the way we often use:

<span style= "FONT-SIZE:18PX;" >var Pattern=/e/;var pattern=/e/gi;</span>

Detailed analysis of three RegExp objects

(1) RegExp Object Properties


These are basic examples we have seen in the above example, but let's take a few simple examples to see:

<span style= "FONT-SIZE:18PX;" >var Pattern=/e/gim;document.write (pattern.global+ "");//output: TRUE. The description sets the global mode document.write (pattern.ignorecase+ "");//output: Truedocument.write (pattern.multiline+ "");// Output: Truedocument.write (pattern.source+ "");//Output:e</span>

(2) RegExp Object Methods


The RegExp object has 3 methods: Test (), exec (), and compile ().

1) The test () method retrieves the specified value in the string, and the return value is true or false.

<span style= "FONT-SIZE:18PX;" >var Pattern=/e/;var str= "The best things on life is free";d ocument.write (Pattern.test (str));//output: True</span >

2) the EXEC () method retrieves the specified value in the string, the return value is the found value, or null if no match is found. Example one:

<span style= "FONT-SIZE:18PX;" >var Pattern=/e/;var str= "The best things on life is free";d ocument.write (pattern.exec (str));//Output:e</span>

Example two:

Add a second parameter to the RegExp object to set the retrieval. If you need to find all the existence of all the characters, you can use the "G" parameter.

When using the "G" parameter, the EXEC () works as follows:

1 Find the first "E" and store its location.

2 If you run EXEC () again, retrieve it from the stored location and find the next "E" and store its location.

<span style= "FONT-SIZE:18PX;" >var Pattern=/e/g;var str= "The best things on life is free";d o{    var result=pattern.exec (str);    document.write (result+ "");} while (Result!=null) </span>

The result of the output is: E e e e e e null

3) The compile () method is used to change the regular expression, and compile () can either change the retrieval mode or add or remove the second parameter.

<span style= "FONT-SIZE:18PX;" >var Pattern=/e/;var str= "The best things on life is free";d ocument.write (Pattern.test (str));// Output: Truepattern.compile ("D");d Ocument.write (Pattern.test (str));//Output:false</span>

(3) Methods of string objects that support regular expressions


Because regular expressions and string objects have a certain connection, some methods of string objects can be used with regular expressions:

<span style= "FONT-SIZE:18PX;" >var pattern=/e/g;//Turn on global mode var str= "The best things on life is free";d ocument.write (Str.match (Pattren) + "<br/> ");//output as an array: E,e,e,e,e,edocument.write (Str.search (Pattren) +" <br/> ");//output: 2 (returns the position of the first match) document.write ( Str.replace (Pattren, "a") + "<br/>");//output: Tha bast things in Lifa Ara Fraavar pattern1=/\s/g;//\ s represents the space character document.write (Str.split (PATTREN1));//Output:the,best,things,in,life,are,free</span>

(4) metacharacters are characters that have special meanings:


As these are widely used, we just cite a few examples:

<span style= "FONT-SIZE:18PX;" The >var pattern=/b.ue/;//Point symbol indicates that any character other than the line break is matched. var str= "Blue";d ocument.write (Pattern.test (str));//Output:true</span>

(5) square brackets are used to find a range of characters:


<span style= "FONT-SIZE:18PX;" >var Pattern=/[a-z]oogle/;//[a-z] represents 26 lowercase letters, either of which can match var str= "Woogle";d ocument.write (Pattren.test (str));// Output:true</span>

(6) quantifier


<span style= "FONT-SIZE:18PX;" >var pattern=/go+gle/;//o* means matching at least one 0var str= "Google";d ocument.write (Pattren.test (str));//Output:true</span>

Four Common regular expressions

The main is to look at the variable Patttern pattern string representation of the regular expression. The rest is some of the basic JS things that can be ignored.

(1) Check postal code

<span style= "FONT-SIZE:18PX;" >var pattern=/^[0-9]{6}$/;//must be 6 bits, and are all digital var str=prompt ("Please enter ZIP Code:"); if (Pattern.test (str)) {    alert (" You have entered the correct postal label! ");} else{     alert ("You have entered the wrong postal designator!") ");} </span>

Enter some data to run the result as:

Input: 056500



Input: 123



(2) Simple email address verification

<span style= "FONT-SIZE:18PX;" >var pattern=/^ ([\w\.\-]+) @ ([\w\-]+) \. ([a-za-z]{2,4}) $/;var str=prompt ("Please enter the mailbox name:"), if (Pattern.test (str)) {    alert ("You entered the correct mailbox name!) ");} else{     Alert ("You entered the wrong mailbox name! ");} </span>
(3) Check the upload file compression package

<span style= "FONT-SIZE:18PX;" >var pattern=/[\w]+\.zip|rar|gz/;//\w represents all numbers and letters as well as the underscore var str=prompt ("Please enter the name of the compressed package:"); if (Pattern.test (str)) {    Alert ("You have entered the correct compression package name!") ");} else{     alert ("You have entered the wrong compression package name!") ");} </span>
(4) Check the phone number
<span style= "FONT-SIZE:18PX;" >var Pattern=/^[1][0-9]{10}$/;var str=prompt ("Please enter mobile number:"); if (Pattern.test (str)) {    alert ("You entered the correct mobile number!) ");} else{     alert ("You're entering the wrong mobile number!) ");} </span>

The results of the following three outputs are no longer one by one displayed, as long as the pattern regular expression is written to verify that the input data is correct. As a result of just touching

Regular expressions, which may have an incorrect place, will be perfected and corrected.


Easy Learning JavaScript 14: JavaScript's RegExp object (regular expression)

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.