| Categories | Latest | Search | Login |

Back

Javascript Regular Expressions



Flags:
   g : Globally matches everything
   i : Ignore case
   m : Match over multiple lines


MATCH

Matching is the basic use of regular expressions, learn this and the advanced stuff will be easy.

These following variation are to demonstrate ranges and quantities:


var str = "123456".match(/[0-9]{6}/g)

With this result: 123456


var str = "12345".match(/[0-9]{6}/g)

With this result: null


var str = "12345".match(/[0-9]{5,6}/g)

With this result: 12345


var str = "rabbit".match(/[a-z]{5,6}/g)

With this result: rabbit


var str = "Rabbit".match(/[a-z]{5,6}/g)

With this result: abbit


var str = "Rabbit".match(/[a-zA-Z]{5,6}/g)

With this result: Rabbit

Notice how this one is case insensitive:


var str = "Rabbit".match(/[a-z]{5,6}/gi)

With this result: Rabbit


var str = "B0bB1n5".match(/[a-zA-Z0-9]{7}/g)

With this result: B0bB1n5

Instead of using [A-Za-z0-9_] it's possible to use w instead:


var str = "B0bB1n5".match(/w{7}/g)

With this result: B0bB1n5


You can mix and match any which way you want:


var str = "12AB34CD".match(/[0-9]{2}[A-Z]{2}[0-9]{2}[A-Z]{2}/g)

With this result: 12AB34CD


var str = "12AB34CD".match(/[0-3]{2}[A-C]{2}[7-9]{2}[X-Z]{2}/g)

With this result: null


var str = "12AB89YZ".match(/[0-3]{2}[A-C]{2}[7-9]{2}[X-Z]{2}/g)

With this result: 12AB89YZ


EMAIL CHECKER

This bit of regex checks for a valid email. The 'i' at the finish makes this case insensitive:
var strValue = "a@b.com"; 
var objRegExp = /(^[a-z]([a-z_.]*)@([a-z_.]*)([.][a-z]{3})$)|(^[a-z]([a-z_.]*)@([a-z_.]*)(.[a-z]{3})(.[a-z]{2})*$)/i; 
var x = objRegExp.test(strValue); 
document.write(x); 

With this result: true


REPLACE

Here's how to do a simple replace. The 'g' on the end tell's regex to match all occurrences:

var str = "I told you it'd be alright!".replace(/alright/g,'a problem'); 

And this is what str now contains: I told you it'd be a problem!


SPLIT

Split's are simple as well:
var myarray = "Let's make a list, or something?".split(/s/g) 

Which results with: Let's,make,a,list,,or,something?



Back

rabbit By rabbit Created on 18th of April 2010, at 10.54 pm
Modified on 21st of June 2010, at 8.25 pm
Category: Javascript: General

rabbitin on again!

Other Docs by rabbit

   system and popen
   Ticker Tape Scrollers
   Javascript Regular Expressions
   Simple Popup Dialogues
   Matrix

View all



Digg  del.icio.us  Reddit  Slashdot  StumbleUpon  TwitThis  


COMMENTS


Search Docs


Browse Docs

Programming
     C
     C++
     Python
     Tcl/Tk
     Java
     PHP
     Perl
     HTML
     Javascript
     Other
Computing
     Linux
     Windows
     Security
     Networks
     Graphics
     Gaming
     Other