JavaScript Regular Expression and samples

                     The regular expression’s elements specify what you would like to match or replace. The flags specify whether the matching/replacing must be done in the case-insensitive (i) and/or global (g) and/or multiline (m) mode.
To create a regular expression, you can use a regular expression literal or the RegExp constructor.

Regular expression literals in JavaScript use this syntax:
/elements/flags or, without the optional flags, simply:
/elements/

Examples of regular expression literals:
re = /^\s+|\s+$/g // any number of leading/trailing whitespaces
re = /\d\d\d/ // one sequence of 3 digits (1st match only)
re = /\d\d\d/g // any sequence of 3 digits
re = /[0-9][0-9][0-9]/g // any sequence of 3 digits
re = /jan|feb|mar|apr/i // Jan or Feb or Mar or Apr (case-insensitive)
re = /”[a-z]+”/gi // any sequence of Latin letters, in quotes

The RegExp constructor has this syntax:
new RegExp(elements,flags)

Examples of the RegExp constructor (the constructor calls below create regular expressions similar to the above):
//to get \s in regular expression, pass \\s to RegExp constructor!
re = new RegExp(“^\\s*|\\s*$”,”g”)
re = new RegExp(“\\d\\d\\d”,”)
re = new RegExp(“\\d\\d\\d”,’g’)
re = new RegExp(“[0-9][0-9][0-9]”,”g”)
re = new RegExp(“jan|feb|mar|apr”,”i”)

Whether you use constructors or literals, your regular expressions can include the following elements and flags. The elements describe the pattern you want to match, while the flags specify how the matching should be performed.

Element Matches this…
[xyz] Any one character x or y or z, as listed in square brackets
[x-z] Any one character within the range specified in brackets
[^xyz] Any one character except x, y, z
[^x-z] Any one character except the range in brackets
. Any character except newline
\d \D Any digit (\d), any non-digit (\D)
\s \S Any whitespace (\s), any non-whitespace (\S)
\w \W Any word character (\w), any non-word character (\W)
\b \B Word boundary (\b), non-boundary (\B)
[\b] Backspace (the square brackets help distinguish backspace from word boundary)
^ Beginning of string; beginning of line if the m flag is set
$ End of string; end of line if the m flag is set
\n \r \f \t \v Newline, carriage return, form feed, tab, vertical tab
\+ \- \. \* \? \| Match + – . * ? | etc. verbatim (not as a special character)
\/ \\ \^ \$ Match / \ ^ $ verbatim (not as a special character)
\[ \] \( \) \{ \} Match brackets/parentheses/braces verbatim
\xAB Match the character with hexadecimal code AB
\uABCD Match the Unicode character with hexadecimal code ABCD

x|y Match x or y
+ Match the preceding element one or more times
* Match the preceding element zero or more times
? Match the preceding element zero or one time
{n} Match the preceding element exactly n times
{n,} Match the preceding element n or more times
{m,n} Match the preceding element at least m, at most n times

(…) Match … as a capturing group: store the matching substring
(used with string.match(re) to return an array of matching strings)
\1 \2 \3 etc. Match the same substring as in capturing group number 1, 2, 3 etc.
$1 $2 $3 etc. Replace with the characters that matched group number 1, 2, 3 etc.
(used in the second argument of replace() method)
(?:…) Match … as a non-capturing group: grouping only, no storing

Any character Match the character verbatim
(except the above)
RegExp flags can be any combination of the following:

i Ignore case (both lowercase and uppercase letters will match)
g Global (allow multiple matches)
m Multiline (^ and $ will match the beginning/end of lines)
The effect of not setting these flags is as follows:
i not set The regular expression is case-sensitive
g not set Use only the first match (no global search)
m not set ^ and $ match the beginning/end of the entire string
Notes
(1) A whitespace (\s) in a regular expression matches any one of the characters: space, formfeed (\f), newline (\n), return (\r), tab (\t), vertical tab (\v), non-breaking space (\xA0), as well as the Unicode characters \u00A0 \u2028 \u2029.

(2) When using the RegExp constructor: for each backslash in your regular expression, you have to type \\ in the RegExp constructor. (In JavaScript strings, \\ represents a single backslash!) For example, the following regular expressions match all leading and trailing whitespaces (\s); note that \\s is passed as part of the first argument of the RegExp constructor:

re = /^\s+|\s+$/g
re = new RegExp(‘^\\s+|\\s+$’,’g’)

Regular Expression samples

*) Trimming a string in JavaScript
To remove all leading and trailing spaces from a string, we can use this code:

function Trim(strValue) {
var pattern = /^\s+|\s+$/g ;
strValue = strValue.replace(pattern, “”);
return strValue;
}

function TrimRight(strValue) {
var patternR = /(\s)+$/g;
strValue = strValue.replace(patternR, “”);
return strValue;
}

function TrimLeft(strValue) {
var patternL = /^(\s)+/g;
strValue = strValue.replace(patternL, “”);
return strValue;
}

This code example uses the regular expression /^\s+|\s+$/g which matches one or more occurrences of whitespace (\s) in the beginning and at the end of string. The g (global) flag in the regular expression specifies that a global search should be performed (e.g. even if a match is found in the beginning of the string, the matching process must still continue and attempt to find whitespaces at the end of the string, too). The string.replace() method is used to replace all leading and trailing whitespace characters with an empty string.

*) Is Null check in Javascript
To check whether a string is empty or not in client side, we can use this code:

function IsNull(strValue) {
//check the string is defined or not
if (!strValue) { return true; }

var pattern = /^\s+|\s+$/g ;
strValue = strValue.replace(pattern, “”);
if (strValue.length > 0) { return false; }
else { return true; }
}
This code example uses the regular expression /^\s+|\s+$/g which matches one or more occurrences of whitespace (\s) in the beginning and at the end of string. After that we will check the length of the string.

*) Decimal check in Javascript
To check whether a number is decimal or not in client side, we can use this code:

function decimalValidation(value) {
var pattern = /^\d*.\d*$/; // var pattern = /^\d*.\d{0,2}$/;
if (value.match(pattern) == null) {
return false;
}
else {
if (value == ‘.’) { return false; }
else { return true; }
}
}

*) Integer check  in Javascript
To check whether a number is integer or not in client side, we can use this code:

function integerValidation(value) {
var pattern = /^\d*$/; // var pattern = /^\d*.\d{0,2}$/;
if (value.match(pattern) == null) {
return false;
}
else {
return true;
}
}

*) Seperates the components of the number

function numberWithCommas(yourNumber) {
//Seperates the components of the number
var n = yourNumber.toString().split(“.”);
//Comma-fies the first part
n[0] = n[0].replace(/\B(?=(\d{3})+(?!\d))/g, “,”);
//Combines the two sections
return n.join(“.”);
}

Ref: http://www.javascripter.net/faq/creatingregularexpressions.htm

Author : Rony T Sam

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s