JavaScript test() Method
The test() method tests for a match in a string.
This method returns true if it finds a match, otherwise it returns false.
Syntax
RegExpObject.test(string)
Return Value
Type Description
Boolean Returns true if it finds a match, otherwise it returns false
RegExp Object
A regular expression is an object that describes a pattern of characters.
Regular expressions are used to perform pattern-matching and "search-and-
replace" functions on text.
Syntax
/pattern/modifiers;
Example:
var pattern = /hello/i;
var str=”hellow world”;
var result=pattern.test(str);
// result will be true;
Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier Description
i Perform case-insensitive matching
g Perform a global match (find all matches rather than
stopping after the first match)
m Perform multiline matching
Brackets
Brackets are used to find a range of characters:
Expression Description
[abc] Find any character between the brackets
[^abc] Find any character NOT between the brackets
[0-9] Find any character between the brackets (any digit)
[^0-9] Find any character NOT between the brackets (any non-digit)
Metacharacters
Metacharacters are characters with a special meaning:
Metacharacter Description
. Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\char Find a char
Quantifiers
Quantifier Description
n+ Matches any string that contains at least one n
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
Example:
var pattern=/^h/g;
var str='hellow world';
var result=pattern.test(str);
//result=true
Example of Email Validation:
var email= "
[email protected]";
var patt1 = /^[a-z]\S+@\S+\.\S+/i;
var result = patt1.test(email);
//result=true
Example of number only validation:
var num1 = "20122013";
var num2= "2012and2013";
var patt1 =/[^0-9]/g
var result1 = patt1.test(num1);
var result2=patt1.test(num2);
//result1=false
//result2=true
Example of String starts with capital-letter and end with digit validation
var result;
var result;
var num1 = "Ram9";
var startpatt =/^[A-Z]/;
var endpatt =/[0-9]$/;
var startresult = startpatt.test(num1);
var endresult = endpatt.test(num1);
if(startresult==true && endresult==true){
result=true;
}
else{
reslut=false;
}
//result=true;