JavaScript regular Expression Definition method detailed

Source: Internet
Author: User

There are two ways to use regular expressions in JavaScript. The first is to build a RegExp object, and the second is to use "//" to define the Perl style. For example:

The code is as follows Copy Code

var str = ' http://www.111cn.net/';

var reg = new RegExp (' http ', ' I ');
Alert (Reg.test (str));
Or
Alert (/http/.test (str));

The above example is to use two ways to determine if the string str contains HTTP, note the second way//must not use quotes.

The first way to generate an object is that the argument is a string, so you can set the contents of the regular expression dynamically (string concatenation), and the second does not. We know that there are many special characters in the regular expression, such as., *,?, and so on, if you need to match these special characters in an expression, you need to use the escape character "". In particular, it is necessary to use two "" when the first type of escape character is handled. For example:

The code is as follows Copy Code

var str = ' http://www.111cn.net/';

var reg = new RegExp (' www\. ', ' I '); Two are used here
Alert (Reg.test (str));
Or
Alert (/www./.test (str));

So why use \ to escape? Because the first method is "compiled", it will become the second way. For example, alert (New RegExp (' www\. ', ' I ')) results in/www./i.

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.