24 September 2013

Regular Expressions in javascript

When dealing with regular expressions in javascript the following is the way to declare and use them.

Normally in java we declare the regEx as strings.


For example:-


String regEx=”\d{1,3}”;


But in javascript they are no numbers or strings. There is a specific appraoach to declare regEx.


For Example:-


var re5digit=/^\d{5}$/;


In the above the regEx have started  with “/” and also ended with “/”.


Small example for validating input in javascript :-


var re5digit=/^\d{5}$/;
var value=”str123”;
if (value.search(re5digit) == -1) //if match failed
       alert("Please enter a valid 5 digit number inside form");
}

No comments: