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("dailycoding"))
{
  // Success
}
else
{
  // Fail
}

If you want to extract multiple matched from the input string

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

Regular Expression Tester

Here is an online regular expression tester you can use to create and validate regular expressions

10 comment(S)


singh on Aug 26, 2010 03:29 AM


singh on Aug 26, 2010 03:29 AM


dgdf on Apr 4, 2011 03:50 AM


dgdf on Apr 4, 2011 03:50 AM


Yoel on Jun 26, 2011 01:08 PM

Excellent.
Thank you very much!

Ryan on Sep 23, 2011 04:17 PM

I found many sites with explanations of what Regular Expressions are, but none of them showed how to actually use them so simply. Thank you!

hgfhbdg on Feb 21, 2013 12:41 AM


ghj on Apr 15, 2013 11:10 PM


ghj on Apr 15, 2013 11:10 PM


sponsored

ghj on Apr 15, 2013 11:10 PM

fdg

Leave a comment