Regular Expression in Javascript - Matching End of Subject



Let us assume that we want to find if a string contains a certain pattern at its end. We append the pattern with the special character $ to accomplish the task. In the following real world example we will try to find if the string contains “.com” in the end.

<html>
<body>
<script type="text/javascript">
<!--
/*
********************************************************
Javascript Regular Expression Example 4
Anchoring with $
********************************************************
*/
var pattern1=new RegExp("com$");
var string1 = new Array(2);
string1[0] = "http://yahoo.com";
string1[1] = "http://google.org";
var i;
for(i=0; i<=1; i++)
{
if (pattern1.test(string1[i]))
{
document.write(string1[i], "is a valid .com site","<br\>");
}
else
{
document.write(string1[i], "is not a valid .com site","<br\>");
}
}
//-->
</script>
</body>
</html>

Try this Example online


You can try this example online at - here .

If we run this code, we should get the following output.

http://yahoo.com is a valid .com site http://google.org is not a valid .com site

Note that ("com$").test("http://google.org") returns false not only because it does not contain .com but also because it does not contain .com in the end. The ("com$").test("http://yahoo.com/profile/vikasshukla") will return false because, even though there is a .com in the string http://yahoo.com/profile/vikasshukla, it is not at the end of the string.

At this point you would like to take the tests to strengthen your understanding. Click next to continue.