Using RegEx(Regular Expressions) in JavaScript


Javascript has built-in support for regular expression in almost all browsers. This means you can use regular expression at client side too. You can use to validate the user’s input data at client side itself to reduce the server side processing, however you may want to check those at server side too for security problems.

To use regular expression in javascript you can use the RegExp object

var myRegExp = new RegExp("[a-zA-z]+");

Or you can directly creates its instance by using special syntax

var myRegExp = /[a-zA-z]+/

To test a string against a RegExp

var myRegExp = /[a-zA-z]+/;
if(myRegExp.test("codinghint"))
{
  // Success
}
else
{
  // Fail
}

If you want to extract multiple matched from the input string

var myRegExp = /[a-zA-z]+/;
var inputString = "www.codinghint.com";
var myMatches = document.frm1.txt1.value.match(myRegExp);
for(var i=0; i<myMatches.length; i++)
{
  alert(myMatches[i]);
}
Advertisements

4 thoughts on “Using RegEx(Regular Expressions) in JavaScript

  1. Simply wish to say your article is as astonishing. The clearness in your post is simply nice and i could assume you’re an expert on this subject. Fine with your permission let me to grab your feed to keep updated with forthcoming post. Thanks a million and please keep up the enjoyable work.

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