Regular Expressions In JavaScript

Regulars expressions are a sort of shorthand , these are used in pattern matching and substitutions. A regular expression is just sequence or a pattern of characters that is matched against a string of text. Regexps are very powerful and useful tool. They contain a lot of meaning in a short space. Every single character in the regular expression has some meaning. Any regular expression should start with a / (slash) sign and end with a slash (/) sign. The below given example can explain the power of regular expressions. In this example 5 digits are to be entered by user, when user clicks on the button function ff is called and the value entered is checked with the regular expression. In the regular expression is /^\d{5}$/
 
/ – start of regular expression
^ – to start the matching from first character
\ – indicates digit character
{5} – indicates that 5 , because it is preceded by \d which means digit character , so \d{5} means 5 digit characters
$ – indicates end of the string
 
The meaning of the above given expression is starting from beginning of the string there must be nothing other than 5 digits and There must also be nothing following those 5 digits.
 
<html>

<head>

</head>

<body>

<script>

 

function ff(f1)

{

var a=f1.t1.value

var re5=/^\d{5}$/

if (a.search(re5)==-1)

{

alert(‘Enter Valid number’)

}

else

{

alert(‘good try’)

}

 

}

</script>

 

<form name=f1>

Enter Five digits code :<input type=”text” name=t1> <br>

<input type=”button” value=” hit me to check the number ” onclick=”ff(f1)”>

</form>

</body>

</html>

Scroll to Top