JavaScript Regular expression syntax and usage examples Daquan

Source: Internet
Author: User

JavaScript Regular Expressions

1. Using the JS regular expression, first of all to understand the JS regular expressions commonly used symbols, such as:

/.../

Represents the beginning and end of a pattern

^

Match the start of a string

$

Match the end of a string

\s

Match a white space character

\s

Match a non-whitespace character

\d

Matches a numeric character, equivalent to [0-9]

\d

Matches a non-numeric character, equivalent to [^0-9]

\w

Match a number, letter, or underscore equivalent to [a-za-z0-9_]

.

Match a character other than the line break

\

Escape character, for these special symbols above, if you want to match, you need to add \ to escape

N

Matches the previous n times

{N,}

Match previous item n to multiple

{N,m}

Matches the previous item n to M times, that is, the minimum match n times, the most matches m times

*

Matches the previous item 0 to several times, equivalent to {0,}

+

Matches the previous item 1 to several times, equivalent to {1,}

?

Matches the previous item 0 to 1 times, equivalent to {0,1}

2. Using regular expressions

Using regular expressions, you need a RegExp object (RegularExpression) that uses the method of the object to validate the output

Whether the content conforms to the rules.

There are two ways to create a regular expression:

1. Common method: var reg=/expression/additional parameters;

2. Construction method: var reg=new RegExp (expression, additional parameters);

Additional parameters, which can be understood as a pattern, include the use of expressions to restrict, and then add some common filtering patterns. Such as

G

Global match

I

Ignore case matching

M

Multi-line matching

Rules for attaching parameters:

1. Parameters can be used together, of course, can not add.

2. Expressions can also write strings directly.

3. The expression in the normal way must be a constant, but you can use a variable in an expression in the constructor method.

Common methods for regular expressions:

1. RegExp object's Test (string to be examined) method, how to conform to the rule return true, otherwise return false;

2. The search (reg) method of the string object to find if the string contains a string that matches the rule

3. Replace (reg) method of a String object, replacing the string in the string that matches the rule

4. The Split (reg) method of the string object, which splits the source string into groups according to a string that conforms to the rule.

Additional usage Examples:

/*

Purpose: Check the correct format of incoming email

Input:

Stremail: String

Return:

False if True is returned by validation

*/

function Checkemail (stremail) {

var emailreg =/^[_a-z0-9]+@ ([_a-z0-9]+\.) +[a-z0-9]{2,3}$/;

var emailreg =/^[\w-]+ (\.[ \w-]+) *@[\w-]+ (\.[ \w-]+) +$/;

if (Emailreg.test (Stremail)) {

return true;

}else{

Alert ("The email address you entered is not in the correct format!") ");

return false;

}

}

/*

Purpose: Verify the format of the IP address

Input: Strip:ip Address

Returns: False if True is returned by validation;

*/

function IsIP (StrIP) {

if (IsNull (StrIP)) return false;

var re=/^ (\d+) \. (\d+) \. (\d+) \. (\d+) $/g//matching regular expressions for IP addresses

if (Re.test (StrIP))

{

if (regexp.$1 <256 &&regexp.$2<256 && regexp.$3<256 && regexp.$4<256) return true;

}

return false;

}

/*

Purpose: Check whether the input phone number is correct

Input:

S: string

Return:

False if True is returned by validation

*/

function Checkmobile (s) {

var regu =/^[1][3][0-9]{9}$/;

var re = new RegExp (Regu);

if (Re.test (s)) {

return true;

}else{

return false;

}

}

/*

Purpose: Check the input phone number format is correct

Input:

Strphone: String

Return:

False if True is returned by validation

*/

function Checkphone (strphone) {

var phoneregwitharea =/^[0][1-9]{2,3}-[0-9]{5,10}$/;

var phoneregnoarea =/^[1-9]{1}[0-9]{5,8}$/;

var prompt = "The phone number you entered is incorrect!"

if (Strphone.length > 9) {

if (Phoneregwitharea.test (Strphone)) {

return true;

}else{

alert (prompt);

return false;

}

}else{

if (Phoneregnoarea.test (Strphone)) {

return true;

}else{

alert (prompt);

return false;

}

}

}

/*

Purpose: Check whether the input string is empty or all spaces

Input: str

Return:

Returns true if all is null, otherwise false

*/

function IsNull (str) {

if (str = = "") return true;

var Regu = "^[]+$";

var re = new RegExp (Regu);

return Re.test (str);

}

/*

Purpose: Checks whether the value of the input object conforms to the integer format

Input: string for str input

Returns: False if True is returned by validation

*/

function Isinteger (str) {

var regu =/^[-]{0,1}[0-9]{1,}$/;

return Regu.test (str);

}

/*

Purpose: Checks whether the input string conforms to the positive integer format

Input:

S: string

Return:

False if True is returned by validation

*/

function Isnumber (s) {

var Regu = "^[0-9]+$";

var re = new RegExp (Regu);

if (S.search (re)! =-1) {

return true;

} else {

return false;

}

}

/*

Purpose: Check whether the input string is a numeric format with decimals, which can be negative

Input:

S: string

Return:

False if True is returned by validation

*/

function Isdecimal (str) {

if (Isinteger (str)) return true;

var re =/^[-]{0,1} (\d+) [\.] + (\d+) $/;

if (Re.test (str)) {

if (regexp.$1==0&&regexp.$2==0) return false;

return true;

} else {

return false;

}

}

/*

Purpose: Checks whether the value of the input object conforms to the port number format

Input: string for str input

Returns: False if True is returned by validation

*/

function Isport (str) {

Return (Isnumber (str) &&str<65536);

}

/*

Purpose: Check whether the input string conforms to the amount format

The format is defined as a positive number with decimals, up to three digits after the decimal point

Input:

S: string

Return:

False if True is returned by validation

*/

function Ismoney (s) {

var Regu = "^[0-9]+[\." [0-9] {0,3}$ ";

var re = new RegExp (Regu);

if (Re.test (s)) {

return true;

} else {

return false;

}

}

/*

Purpose: Check whether the input string is composed only of English letters and numbers and underscores

Input:

S: string

Return:

False if True is returned by validation

*/

function Isnumberor_letter (s) {//To determine whether it is a number or a letter

var Regu = "^[0-9a-za-z\_]+$";

var re = new RegExp (Regu);

if (Re.test (s)) {

return true;

}else{

return false;

}

}

/*

Purpose: Check whether the input string is composed only of English letters and numbers

Input:

S: string

Return:

False if True is returned by validation

*/

function Isnumberorletter (s) {//To determine whether it is a number or a letter

var Regu = "^[0-9a-za-z]+$";

var re = new RegExp (Regu);

if (Re.test (s)) {

return true;

}else{

return false;

}

}

/*

Purpose: Check whether the input string is only composed of Chinese characters, letters, numbers

Input:

Value: String

Return:

False if True is returned by validation

*/

function Ischinaornumborlett (s) {//Determine whether it is a Chinese character, a letter, a number composition

var Regu = "^[0-9a-za-z\u4e00-\u9fa5]+$";

var re = new RegExp (Regu);

if (Re.test (s)) {

return true;

}else{

return false;

}

}

/*

Purpose: To determine whether it is a date

Input: Date: Dates; FMT: date format

Returns: False if True is returned by validation

*/

function isDate (date, FMT) {

if (fmt==null) fmt= "YYYYMMDD";

var yindex = fmt.indexof ("yyyy");

if (yindex==-1) return false;

var year = date.substring (yindex,yindex+4);

var mindex = Fmt.indexof ("MM");

if (mindex==-1) return false;

var month = date.substring (mindex,mindex+2);

var dindex = Fmt.indexof ("dd");

if (dindex==-1) return false;

var day = date.substring (dindex,dindex+2);

if (!isnumber (year) | | Year> "2100" | | year< "1900") return false;

if (!isnumber (month) | | Month> "12" | | month< "") return false;

if (Day>getmaxday (year,month) | | day< "") return false;

return true;

}

function Getmaxday (year,month) {

if (month==4| | month==6| | month==9| | MONTH==11)

return "30";

if (month==2)

if (year%4==0&&year%100!=0 | | year%400==0)

return "29";

Else

Return "28";

return "31";

}

/*

Purpose: Whether character 1 ends with string 2

Input: str1: string; str2: included string

Returns: False if True is returned by validation

*/

function Islastmatch (STR1,STR2)

{

var index = str1.lastindexof (STR2);

if (str1.length==index+str2.length) returntrue;

return false;

}

/*

Purpose: Whether character 1 starts with string 2

Input: str1: string; str2: included string

Returns: False if True is returned by validation

*/

function Isfirstmatch (STR1,STR2)

{

var index = str1.indexof (STR2);

if (index==0) return true;

return false;

}

/*

Purpose: Character 1 is a string containing 2

Input: str1: string; str2: included string

Returns: False if True is returned by validation

*/

function IsMatch (STR1,STR2)

{

var index = str1.indexof (STR2);

if (index==-1) return false;

return true;

}

/*

Purpose: Check that the input start and end date is correct, the rule is two date format is correct,

and end as scheduled >= start date

Input:

StartDate: Start Date, string

EndDate: End as expected, string

Return:

False if True is returned by validation

*/

function Checktwodate (startdate,enddate) {

if (!isdate (StartDate)) {

Alert ("The Starting date is incorrect!");

return false;

} else if (!isdate (endDate)) {

Alert ("The expiry date is incorrect!");

return false;

} else if (StartDate > EndDate) {

Alert ("The start date cannot be greater than the end date!");

return false;

}

return true;

}

/*

Purpose: Check the number of check boxes selected

Input:

CHECKBOXID: String

Return:

Returns the number of selected in this check box

*/

function Checkselect (CHECKBOXID) {

var check = 0;

var i=0;

if (document.all (CHECKBOXID). length > 0) {

For (I=0;i<document.all (CHECKBOXID). length; i++) {

if (document.all (CHECKBOXID). Item (i). Checked) {

Check + = 1;

}

}

}else{

if (document.all (CHECKBOXID). Checked)

check = 1;

}

return check;

}

function GetTotalBytes (Varfield) {

if (Varfield = = null)

return-1;

var totalcount = 0;

for (i = 0; i< varfield.value.length;i++) {

if (varField.value.charCodeAt (i) > 127)

TotalCount + = 2;

Else

totalcount++;

}

return totalcount;

}

function Getfirstselectedvalue (CHECKBOXID) {

var value = null;

var i=0;

if (document.all (CHECKBOXID). length > 0) {

For (I=0;i<document.all (CHECKBOXID). length; i++) {

if (document.all (CHECKBOXID). Item (i). Checked) {

Value =document.all (CHECKBOXID). Item (i). value;

Break

}

}

} else {

if (document.all (CHECKBOXID). Checked)

Value = document.all (CHECKBOXID). value;

}

return value;

}

function Getfirstselectedindex (CHECKBOXID) {

var value =-2;

var i=0;

if (document.all (CHECKBOXID). length > 0) {

For (I=0;i<document.all (CHECKBOXID). length; i++) {

if (document.all (CHECKBOXID). Item (i). Checked) {

value = i;

Break

}

}

} else {

if (document.all (CHECKBOXID). Checked)

Value =-1;

}

return value;

}

function SelectAll (checkboxid,status) {

if (document.all (checkboxid) = = null)

Return

if (document.all (CHECKBOXID). length > 0) {

For (I=0;i<document.all (CHECKBOXID). length; i++) {

document.all (CHECKBOXID). Item (i). checked= status;

}

} else {

document.all (CHECKBOXID). checked = status;

}

}

function Selectinverse (CHECKBOXID) {

if (document.all (checkboxid) = = null)

Return

if (document.all (CHECKBOXID). length > 0) {

For (I=0;i<document.all (CHECKBOXID). length; i++) {

document.all (CHECKBOXID). Item (i). checked=!document.all (CHECKBOXID). Item (i). checked;

}

} else {

document.all (CHECKBOXID). Checked =!document.all (CHECKBOXID). checked;

}

}

function Checkdate (value) {

if (value== ") return true;

if (value.length!=8 | |!isnumber (value)) return false;

var year = value.substring (0,4);

if (year> "2100" | | year< "1900")

return false;

var month = value.substring (4,6);

if (month> "| | | month<") return false;

var day = value.substring (6,8);

if (Day>getmaxday (year,month) | | day< "") return false;

return true;

}

/*

Purpose: Check that the input start and end date is correct, the rule is two date format is correct or all is empty

and end Date >= start date

Input:

StartDate: Start Date, string

EndDate: End Date, string

Return:

False if True is returned by validation

*/

function Checkperiod (startdate,enddate) {

if (!checkdate (StartDate)) {

Alert ("The Starting date is incorrect!");

return false;

} else if (!checkdate (endDate)) {

Alert ("The expiry date is incorrect!");

return false;

} else if (StartDate > EndDate) {

Alert ("The start date cannot be greater than the end date!");

return false;

}

return true;

}

/*

Purpose: Check the security code is correct

Input:

Seccode: Securities Code

Return:

False if True is returned by validation

*/

function Checkseccode (seccode) {

if (Seccode.length!=6) {

Alert ("The length of the security code should be 6 bits");

return false;

}

if (!isnumber (Seccode)) {

Alert ("Security code can only contain numbers");

return false;

}

return true;

}

/*

Function:ctrim (Sinputstring,itype)

Description: Function of string de-whitespace

parameters:itype:1= Remove the space to the left of the string

2= Remove the space to the left of the string

0= remove the left and right spaces of the string

Return value: string with whitespace removed

*/

function Ctrim (sinputstring,itype)

{

var stmpstr = ';

var i =-1;

if (IType = = 0 | | iType = = 1)

{

while (stmpstr = = ")

{

++i;

Stmpstr = Sinputstring.substr (i,1);

}

sinputstring = sinputstring.substring (i);

}

if (IType = = 0 | | iType = = 2)

{

Stmpstr = ";

i = sinputstring.length;

while (stmpstr = = ")

{

I.;

Stmpstr = Sinputstring.substr (i,1);

}

Sinputstring =sinputstring.substring (0,i+1);

}

return sinputstring;

}

JavaScript Regular expression syntax and usage examples Daquan

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.