JavaScript regular Expressions (top)

Source: Internet
Author: User

Regular expressions are generally used to validate client input, while server-side PHP, ASP. NET and other scripts no longer need to be verified, saving the background overhead.

1. Two ways to create

var box=new RegExp ("box", IG); The second argument is a pattern modifier, I means ignoring case, and G is a global match

var box=/box/i;

2. Matching method

(1) Test: Tests if the string matches.

var pattern =new RegExp ("box", I);

var str= "box"; Str= "This is a box! ", also returns true

Alert (Pattern.test (str)); Returns True

  

(2) Exec: Returns the matching array.

var pattern =new RegExp ("box", I);

var str= "box";

Alert (pattern.exec (str));

Note: There are other applications for exec, which will be mentioned later.

3. Regular expression methods that use strings

(1) match (pattern):

var pattern = "Box/ig";//Turn on global

var str= "This is a box! That's a box! "

Alert (Str.match (pattern)); return array [Box,box]

(2) Replace (pattern,replacement): Replace matching elements

var pattern = "box/i";

var str= "This is a box! That's a box! "

Alert (str.replace (Pattern, "Tom")); Returns a tom! That's a box!


(3) Search (pattern): Find the first matching position without the need for a global

(4) Split (pattern): Split into arrays by regular expression

  

JavaScript regular Expressions (top)

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.