Regular Expressions in JavaScript

Discussion in 'JavaScript and AJAX' started by pradeep, Dec 16, 2006.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in

    Introduction



    Regular expressions is a form of pattern matching that you can apply on textual content. Take for example the DOS wildcards ? and * which you can use when you're searching for a file.

    Creating a Regular Expression



    You construct a regular expression in one of two ways:

    1) Using a regular expression literal, as follows:
    Code:
    re = /ab+c/;
    Regular expression literals provide compilation of the regular expression when the script is evaluated. When the regular expression will remain constant, use this for better performance.

    2) Calling the constructor function of the RegExp object, as follows:
    Code:
    re = new RegExp("ab+c");
    Using the constructor function provides runtime compilation of the regular expression. Use the constructor function when you know the regular expression pattern will be changing, or you don't know the pattern and are getting it from another source, such as user input.

    Flags



    There are three flags that you may use on a RegExp. The multiline flag has bad support in older browsers, but the other two are supported in pretty much every browser that can handle RegExp. These flags can be used in any order or combination, and are an integral part of the RegExp.

    Global Search

    g =>The global search flag makes the RegExp search for a pattern throughout the string, creating an array of all occurrences it can find matching the given pattern.

    Ignore Case

    i => The ignore case flag makes a regular expression case insensitive. For international coders, note that this might not work on extended characters such as å, ü, ñ, æ.

    Multiline Input

    m => This flag makes the beginning of input (^) and end of input ($) codes also catch beginning and end of line respectively.

    In almost all cases you can use either way to define a regular expression, and they will be handled in exactly the same way no matter how you declare them.

    Writing a Regular Expression Pattern



    A regular expression pattern is composed of simple characters, such as /abc/, or a combination of simple and special characters, such as /ab*c/ or /go4expert (\d+)\.\d*/. Parentheses are used as a memory device. The match made with this part of the pattern is remembered for later use.

    RegExp Methods



    Some are invoked as a method of a RegExp, whereas others are called as a String's method.

    RegExp.exec(string)

    If no match is found, the method returns null, which converts to a Boolean false, when used as a Boolean expression.

    If at least one match is found, the method returns an array.

    RegExp.test(string)

    The test() method checks if a pattern exists within a string, and returns true if so, and false otherwise. This method doesn't affect the global RegExp object.

    Example:
    Code:
    var email = "pradeep@go4expert.com";
    
    var regex = new RegExp("^[0-9a-z\\._]+@[0-9a-z]+\\..+$","i");
    
    // can also be written as regex = /^[0-9a-z\._]+@[0-9a-z]+\..+$/i;
    
    if (regex.test(email))
    
      alert(email + " is a valid e-mail address!");
    
    else
    
      alert(email + " is an invalid e-mail address!");
    String.match(RegExp)

    This method is the same as exec(), but its object is a string, and its argument is a regular expression.

    String.replace(RegExp)

    The replace() replaces matches with the given string, and returns the edited string.

    Example:
    Code:
    str = "go4expert.com is cool".replace(/cool/,"too cool");
    
    //str is 'go4expert.com is too cool
    String.search(RegExp)

    search() method is the same as test(), but its object is a string, and its argument is a regular expression.

    String.split(RegExp)

    The split() method scans a string (which is actually its object) for delimiters, and splits the string into a list of substrings, returning the resulting list in the form of an array.

    Example:
    Code:
    //We want to get keywords separated either by comma or space
    
    keys = "PHP,Java Perl,Oracle,MySQL MSSQL".split(/[, ]/);
    
    document.write(keys.join("|"));
    
    // outputs PHP|Java|Perl|Oracle|MySQL|MSSQL 
     
  2. asha

    asha New Member

    Joined:
    Nov 9, 2006
    Messages:
    44
    Likes Received:
    2
    Trophy Points:
    0
    Occupation:
    Homemaker
    Location:
    Kolkata
    Home Page:
    http://whatanindianrecipe.com
    A really helpful primer on Javascript regex
     
  3. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83
    I totally agree with you.
     
  4. soham

    soham New Member

    Joined:
    Dec 16, 2006
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Home Page:
    http://www.icelebz.com
    What is a regular expression to match an URL?

    What is a regular expression to match an URL?
     
  5. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Here is the URL regex syntax.

    Code:
    <script>
    var url_match = /https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w/_\.]*(\?\S+)?)?)?/;
    
    alert(url_match.test("http://www.go4expert.com/showthread.php?t=2262"));
    
    </script>
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice