How to use regular expressions in javascript

Source: Internet
Author: User
This article mainly introduces how to use regular expressions in Javascript. it is very detailed and contains simple examples. we recommend this article to you. Usage

1. create an expression

Method for creating a regular expression class in JavaScript:

Var regex = new RegExp ("\ d {5}") or 2.var regex =/\ d {5}/(recommended)

/Expression/is the syntax provided by JavaScript to simplify the preparation of regular expressions. the regular expressions written in // do not need to be escaped.

RegExp object method:

2. determine whether a match exists.

Test (str) checks whether the string str matches a regular expression, which is equivalent to IsMatch.

The code is as follows:


Var regex =/. + @. + /;
Alert (regex. test ("a@ B .com "));
Alert (regex. test ("AB .com "));

3. get matching results

Exec (str) performs search Matching. the returned value is the matching result (*), which is equivalent to match () and matches () in c ()

If exec () finds the matched text, an array of results is returned (a fully matched string and the results of the extraction group .). Otherwise, null is returned. To extract multiple data, you must call the exec () method repeatedly, which is similar to the matches () method.

Note the global mode /..... /G

In non-global mode, an exec () call is equivalent to match ();

Multiple consecutive calls in global mode are equivalent to matches ()

--- I case-insensitive

--- M multi-row matching

The above content is an introduction to the use of regular expressions in javascript. I hope you will like it.

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.