Learn Javascript Tutorials, CSS Tutorials, HTML Tutorials and jQuery Tutorials

Learn CSS, HTML, JavaScript, jQuery and Ajax step by step from beginning to advance with examples and references. Apart from that, beginners can learn tricks and tips.more>>

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">
<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("No match");


<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>

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

No comments: