Skip to main content

Regular expressions in JavaScript

JavaScript includes full support for Perl-style regular expressions, and it's extremely useful for string matching processes.



Coding a script to check sensitive user data is sometimes pretty straightforward. But most of the time this process is not so easy. With current websites, we'll
need to check the proper standardized format of an email address or a URL. That would be a nightmare for programmers, not to mention a confusing and inefficient error-prone process for checking data validity.



A regular expression is a way of describing a pattern in a piece of text. In fact, it's an easy way of matching a string to a pattern. We could write a simple regular expression and use it to check, quickly, whether or not any given string is a properly formatted user input.




Here are a few special characters that can be used for matching characters in regular expressions:


\n // a newline character


. // any character except a newline


\r // a carriage return character


\t // a tab character


\b // a word boundary (the start or end of a word)


\B // anything but a word boundary.


\d // any digit (same as [0-9])


\D // anything but a digit (same as [^0-9])


\s // single whitespace (space, tab, newline, etc.)


\S // single nonwhitespace.


\w // A ?Ąăword character?? (same as [0-9a-zA-Z_])


\W // A ?Ąănonword character (same as [^0-9a-zA-Z_]


match()

Verify Phone number (123) 456-7890






validateForm = function() {

if ( checkPhone( this.phone, 'Please enter a valid phone number') ) {

return true;

}

return false;

}

checkPhone= function( field, errorMsg) {

phoneRegex = /^\(\d{3]\) \d{3}-\d{4}$/;

if( !field.match( phoneRegex ) ) {

alert( errorMsg );

field.focus();

field.select();

return false;

}

return true;

}


replace()


function formatField( fieldValue ) {

return fieldValue = fieldValue. replace(/\n/g, Ą°<br />Ąą);

}


search()


pos = htmlString.search(/^<a href="http:\/\/$/i);

if ( pos != -1) {

alert( 'First absolute link found at ' + pos +'position.');

}

else {

alert ( 'Absolute links not found');

}



test()




The test() method is somewhat particular and different from the rest, as we'll
see shortly. Within the JavaScript context, when a pattern is defined following
the syntax previously described, we are actually defining a new object, called
a ?Ąăregular expression object??. All we need to know is that this object owns
the proprietary test() method, which allows us to perform string matching according
to a given string.


The test() method takes a given string as a parameter and looks for matches
according to the pattern defined within the regular expression object itself.
If any matches are found, it will return true. If no matches are found, then
it will return false. Let's see an example to explain how this method works:


function validateEmail ( emailField, errorMsg ) {

emailpat = /^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/;

if( !emailpat.test( emailField.value ) ) {

alert( errorMsg);

emailField.focus();

emailField.select();

return false;

}

return true;

}


To validate an email address, we should call the function as:


validateEmail( this.email , 'Please enter a valid email address');




Comments

Popular posts from this blog

user Emulator to debug Windows Mobile 6 in Vista

open Windows Mobile Device center Mobile Device Setting -> Connection Setting -> Allow connections to one of the following: Change to DMA in vs 2008, Go to Tools -> Device Emulator Manager select one from list, for example: windows mobile 6 professional emulator right on to cradle waiting for popup to establish the relationship (be sure get internet connection from Emulator)

android textsize sp, px, dp

android:textSize Since:  API Level Size of the text. Recommended dimension type for text is "sp" for scaled-pixels (example: 15sp). Must be a dimension value, which is a floating point number appended with a unit such as " 14.5sp ". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters). This may also be a reference to a resource (in the form " @[ package :] type : name ") or theme attribute (in the form " ?[ package :][ type :] name ") containing a value of this type. This corresponds to the global attribute resource symbol  textSize .

Request Signatures in Blackberry

Request Signatures in Blackberry need copy sigtool.db, sigtool.csk to SDK/component/Bin folder for example V 4.2.1 ../eclipse\plugins\net.rim.eide.componentpack4.2.1_4.2.1.17\components\bin