SunQuest
 
       JavaScript
  Home arrow JavaScript arrow Page 8 - Regular expressions in JavaScript
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Actuate Whitepapers 
VeriSign Whitepapers 
IBM® developerWorks 
Sun Developer Network 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
JAVASCRIPT

Regular expressions in JavaScript
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 138
    2004-12-20

    Table of Contents:
  • Regular expressions in JavaScript
  • The Basics
  • Character Escaping
  • Repetition
  • Counted Subexpressions
  • Using regular expressions in JavaScript
  • The match() method
  • The replace() method
  • The test() method

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT

    Stay one step ahead of the competition. Evaluate and give feedback on some of the hottest web development tools on the market today. Make your opinion heard! Click Here

    Regular expressions in JavaScript - The replace() method


    (Page 8 of 9 )

    As you might suppose, replace() method replaces matches to a given regular expression with some new string. For a simple example, let’s say we want to replace every newline character (\n) with a break <br /> tag, within a form field used for comments, by formatting the content for proper displaying.

    For example:

    comment = document.forms[0].comments.value;  // assumes that our HTML form the first one present in the document, and it has a field named “comments”

    comment = comment.replace(/\n/g, “<br />”);

    Pretty simple, right?, The first parameter taken is the regular expression we’re searching for (please note the g modifier indicating that it will do a global search, so it will find all of the occurrences in the string, not just the first). The second argument or parameter is the string with which we want to replace any matches (in this case, the <br /> tag).

    Let’s wrap the above code into a simple function:

    function formatField( fieldValue ) {
     return fieldValue = fieldValue. replace(/\n/g, “<br />”);
    }

    The function accepts any string as a parameter, and returns the new string with all of the newline characters replaced by <br /> tags.

    In a moment, we’ll see another useful method used with regular expressions: the search() method.

    The search() method

    The search() method is very similar to the indexOf() method, with the difference being that it takes a regular expression as a parameter instead of a string. Then it searches the string for the first match to the given regular expression and returns an integer that indicates the position in the string (strings in JavaScript are zero-indexed elements, so it would return 0 if the match is at the start of the string, 5 if the match begins with the 5th character in the string, and so on). If no match is found, the method will return –1.

    Let’s say we wish to know the location of the first absolute link within a HTML document. We might code something like this:

    pos = htmlString.search(/^<a href=”http:\/\/$/i);
    if ( pos != -1) {
     alert( ‘First absolute link found at’ + pos +’position.’);
    }
    else {
     alert ( ‘Absolute links not found’);
    }

    It’s very simple and not quite useful, but good enough for example purposes.

    So far, all methods described here work by accepting a regular expression as the parameter. Now, let’s take a detailed look at our final method: test(), which is by far the most used to perform client-side validation when using regular expressions in JavaScript.

    More JavaScript Articles
    More By Alejandro Gervasio


       · The phone number validation code does not work per the article. Not only that, but...
       · my code did not cut and paste well as you can see above. You may test it out on my...
       · Sorry it took me so long to reply back.Your commnents is always welcome. The...
       · Hi again,I checked your code at your server and it's working just fine....
       · hitiy need to change the quotes from `eg validateEmail( this.email , `Please...
       · Yes, there is an error about the quotes. Due to program incompatibility.Just...
       · Yes, there is an error about the quotes. Due to program incompatibility.Just...
       · In the code a ] was inadvertenly placed instead of a }. Probably a typo - forgot to...
       · Hi Htarko,Thank you for commenting on this article, and of course thank you for...
       · I read your article.. It's fine.. But I couldn't find the regular expression for...
       · Thank you for commenting on my JavaScript article. Regarding your question, you can...
     

    JAVASCRIPT ARTICLES

    - Using the Style Object for Zebra Tables with...
    - Binary Searching
    - An Improved Approach to Building Zebra Tables
    - Assigning Background Colors Dynamically to Z...
    - Building Zebra Tables with CSS and JavaScript
    - JavaScript: Array Objects
    - A Closer Look at Smart Markers with Yahoo! M...
    - Using Polylines and Smart Markers with Yahoo...
    - Bulleted Menu of Links
    - Creating Click Loggers and Basic Markers wit...
    - Adding Pan Controls to Yahoo! Maps
    - Adding Zoom Controls to Yahoo! Maps
    - Working with Yahoo! Maps
    - Building Image Zooming Controls with the DOM...
    - Working with Multiple Graphics for a Zoom Ap...







    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway