About the Blog:

This blog is dedicated to all the front-end and UI developers who wants to excel their skills in CSS, HTML, JavaScript, jQuery, Ajax, Reactjs, Angularjs, Front-end standards and in Rich User Experiences. In this blog, we are sharing some useful tips and tricks along with the code snippet examples which will help you to build responsive and user friendly websites/web applications.

Wednesday, August 20, 2008

Introduction to Regular Expressions - RegExp( )

Regular Expressions are very useful and commonly used for creating pattern matches, pattern searches, etc. for Strings in JavaScript. There is another method called indexOf() method which works almost same like regular expressions but for advance and complex pattern searches, regular expressions are used.

For creating a regular expression as an object, we can simply write:

new RegExp("\/D\");

Regular expressions are clearly defined by example given below:


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>

<script language="JavaScript">
<!--
// created BY: rjs
function demoMatchClick()
{
var re =/[0-9]/g;
// For Numeric Value use /[0-9]/ or /\d/ and for non-numeric value use /\D/ or /[^0-9]/
// /[0-9a-zA-Z] for numeric as well as character(small/caps) for non-aplha --> use this /[^a-zA-Z]/.
// /[^a-zA-Z]/g here (g) for global search anywhere in the string even mix-up string.

// match(), search(), replace(), split()
// For Constructor -----> exec(), compile(), test()

var mat=document.demoMatch.subject.value.match(re);

if (mat)
{
alert(mat);
}
else
{
alert("No match");
}
}

</script>
</head>

<body>
<form id="demoMatch" NAME="demoMatch" METHOD="POST">
<P>Subject Number: <INPUT TYPE=TEXT NAME="subject"
VALUE="" SIZE=50></P>
<P><INPUT TYPE=SUBMIT VALUE="Test Match" ONCLICK="demoMatchClick()"></P>
</form>
</body>


Other Useful Resources:
Javascript Completed Reference - Regular Expressions
Basics of Regular Expressions

No comments: