Alternate way of expressing pattern



So far we have expressed the patterns to be matched using the RegExp() constructor. There is an alternate way of doing the same thing using special literal syntax. In the alternate way, the regular expression literals are specified between a pair of forward slash characters.

To give an example the following regular expression literals are equivalent.

var pattern1 = new RegExp("^[1-2]?[0-9]{1}$");
var pattern1 = /^[1-2]?[0-9]{1}$/;
Both of them can be used to find if the given string is a number between 0 and 29. Let us write a complete example using the second method.


<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Javascript Regular Expression Example 
Alternate way
********************************************************
*/
var pattern1 = /^[1-2]?[0-9]{1}$/;
var string1 = new Array(4);
string1[0] = "12";
string1[1] = "54";
string1[2] = "23";
string1[3] = "9d";
var i;
for(i=0; i<=3; i++)
{
if (pattern1.test(string1[i]))
{
document.write(string1[i], " -> match found ","<br\>");
}
else
{
document.write(string1[i], " -> match not found ","<br\>");
}
}
//-->
</script>
</body>
</html>

Try this Example online


You can try this example online at - here .

If we run this script we get the following result.

12 -> match found
54 -> match not found
23 -> match found
9d -> match not found


Special Note for Empty Regular Expression



Regular expression literals can not be empty. An empty regular expression // will confuse the interpreter for a comment. If we do need to specify an empty regular expression literal we use /(?:)/. As we will see later on (?:x) means matches x but does not remember the match.