Regular Expression in Javascript - Anchoring



There are instances where we want to see if the pattern matches a string that starts with a certain pattern. We use special characters for this type of match. These special characters are called anchors. Let us say, we want to search if a string starts with a pattern say - beginning. Here is the code to do that.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Javascript Regular Expression Example3
Anchoring with ^
********************************************************
*/
var pattern1=new RegExp("^beginning");
var string1 = new Array(2);
string1[0] = "beginning of the world was strange";
string1[1] = "in the beginning the world was strange";
var i;
for(i=0; i<=1; i++)
{
if (pattern1.test(string1[i]))
{
document.write(i," Match found","<br\>");
else
{
document.write(i," Match not found","<br\>");
}
}
//-->
</script>
</body>
</html>

Try this Example online


You can try this example online at - here .

If you run the script, you will get the following output

0 Match found
1 Match not found


Take a look at

var pattern1=new RegExp("^beginning");


The literal ^ has a special meaning. It says that the string in which we try to match the patter MUST begin with the pattern following ^. Effectively, ^ matches before the very first character of the string being matched.

When the pattern "^beginning" tries to match the string "beginning of the world was strange", the match is found. However, when it tries to match "in the beginning of the world was strange", the match is not found since it attempts to see if the string "beginning" is right at the start of the string.