| Febuary 20, 2009 |
Using Regulat Expressions in Javascript |
| By: Ranson |
| Fri Feb 20 2009 18:32:42 |
I am going to give a short tutorial on using regular expressions within javascript. Regular expressions are a very powerful part of the programing language that I rarely see any one using. I will post a simple script here and talk more about this later.
function replace() { // removes spaces or carrage returns // \s means any white space (space, carrage return, etc.) // g means do it globally var myExp = /\s/g; var myName = prompt("Please type in a name in Last, First format","Smith, Bill"); // replace any space with an underscore _ var myName2 = myName.replace(myExp,"_"); // will print -> Smith_Bill alert("The name you typed in has been reformated to " + myName2); }
-------------------------------------------------------------------------------------------------
Ledgend of Regular Expressions Operators: \n = new line \r = carrage return \t= tab \d = digit \D = Non digit \w = any word charactor [a-z, 0-9] \W = Non word charactor [$ # * ] \s = White space ( \n, \r, \t, or space ) \S = Non white space . = any single charactor (dot or period) * = zero or more of the previous charactor + = One or more of the previous charactor ? = Zero or one occurance of the previous charactor
With Regular Expressions we always look for a match in a string. if (string == "buba") { do_something(); }
| = or in a regular expression
MyEXP = "/ray|bob/"; (match ray or bob)
Testing for a match ------------------------------------------------------------------------------------------------- Case Sensitive Regular Expression: myExp = /Ray/; myName = "Ray"; var found = myExp.test(myName);
found - would be true because myName was the same as myExp (case sensitive)
------------------------------------------------------------------------------------------------- Case Sensitive Regular Expression: myExp = /ray/; myName = "Ray"; var found = myExp.test(myName);
found - would be false because myName was NOT the same as myExp (case sensitive)
------------------------------------------------------------------------------------------------- Case Insensitive Regular Expression: // the i means case insensitive myExp = /ray/i; myName = "Ray"; var found = myExp.test(myName);
found - would be true because myName was the same as myExp (case insensitive)
------------------------------------------------------------------------------------------------- Regular Expression: // the i means case insensitive myExp = /Buba/i; myName = "Ray"; var found = myExp.test(myName);
found - would be false because myName was not the same as myExp (case insensitive)
------------------------------------------------------------------------------------------------- With any of the above statements, you can use a conditional statement to triger something else in the script.
if (found) { DoThis(); } else { DoOther(); }
Search and Replace
Regular expressions are great to use for stripping charactors from form data that you do not want to be passed to a program. The basic use is very simple, but regular expressions can get complicated, as you will see later.
Lets say you have a form that allows users to type in data. One of the fields on the form you will use for a file name, so you want to strip all the NON Word charactors from the filed.
function CheckFileName() { FileName = "document.FORM.FileName.value"; // Ray & Grace
// \W means any NON Word charactor g means do it globally.
var myExp = /\W/g;
// This replaces any NON Word charactor with nothing. // Form data; "Ray & Grace" becomes "RayGrace"
var myFileName = FileName.replace(myExp,"");
// Now you can write the newly formated data to a hidden field on the form, // or post it on the page.
document.FORM.MyFileName.value = myFileName; }
--------------------------------------------------------------------------------------------------------------------
Same example as above but we replace the Special Charactors with and underscore. The FileName -> Ray & Grace has 3 NON Word charactors in it, the & and 2 spaces.
function CheckFileName() { FileName = "document.FORM.FileName.value"; // Ray & Grace
// \W means any NON Word charactor g means do it globally.
var myExp = /\W/g;
// This replaces any NON Word charactor with an Underscore (times 3). // Form data; "Ray & Grace" becomes "Ray___Grace"
var myFileName = FileName.replace(myExp,"_");
}
In the above function myFileName equals Ray___Grace.
-------------------------------------------------------------------------------------------------------------------- If you do not want all the extra underscores you can strip the spaces first then replace the Special Charactors with the underscore.
function CheckFileName() { FileName = "document.FORM.FileName.value"; // Ray & Grace
// \W means any NON Word charactor g means do it globally.
var myExp1 = /\s/g; // \s means any white space. var myExp2 = /\W/g;
// This replaces any White Space with nothing. var FileName2 = FileName.replace(myExp1,"");
// This replaces any NON Word charactor with an underscore. var myFileName = FileName2.replace(myExp1,"_");
// Form data; "Ray & Grace" becomes "Ray_Grace"
}
In the above function myFileName2 equals Ray_Grace.
-------------------------------------------------------------------------------------------------
Validate User name on a form. We use the test function.
function ValidateUserName() { var Val = document.FORM.username.value;
// The expression below has one space in it. var Exp=/ /;
var found = Exp.test(Val);
if (found) { alert("You can not have spaces in your User Name."); document.FORM.username.value = ""; document.FORM.username.focus(); }
-------------------------------------------------------------------------------------------------
Validate that an email address is formatted corectly. This uses the search function. This is a complicated regular expression, don't let that bother you, it works.
function ValidateEmail() { var Email = document.FORM.Email.value;
// Expression for testing email address var format=/^[^@]+@([-\w]+\.)+[A-Za-z]{2,4}$/;
if(Email.search(format) == -1){ alert("Your Email Address " +Email+ " is not formatted correctly.");
// set switch badEmail = "1"; return false; } }
-------------------------------------------------------------------------------------------------
Reformatting the order of fields to print something to the user or send to a form processor. This function captures the data in variables and is used to rearrange the data.
---------------------------------------------------------------------------------
function StripIt() {
// \s = any white space // \w = any word charactor [a-z, 0-9] // + = One or more of the previous charactor var myExp = /\w+,\s*\w+/;
// Prompt the user for their name. var myName = prompt("Please type in a name in Last, First format","Smith, Bill");
if (myName) { var found = myExp.test(myName); if(found) {
// Capturing the matched data // Here we use brackets around the regular expressions to capture the data. // The first match is stored in a variable $1 // The second match is stored in the next available variable $2
$1 $2 var myExp2 = /(\w+),\s*(\w+)/;
// by using the brackets around the RE's we capture the match // and store it in a variable.
// Smith is stored in $1 variable // Bill is stored in $2 variable
// Here we rearrange the names to "First Last". var myName2 = myName.replace(myExp2,"$2 $1"); alert("The name you typed in has been reformated to " + myName2); } else { alert("The name you typed in was " + myName); } } else { alert("No name was given. Try again."); } }
//The alert prints "Bill Smith".
-------------------------------------------------------------------------------------------------
This is a function I use reguraly to validate ALL form fields.
// this function will validate all fields on the form // all fields must be filled in by the user. // to validate an Email Address, the field name="" must contain the word "email" // ie - emailaddress, email, emailadd, etc. Not case sensitive. // in the "Submit" tag, use the following code - onclick="return ValidateAll(this.form);"
function ValidateAll() { var EmailTest = /email/i; for (i=0;i<document.forms[0].elements.length; i++) { var found = (document.forms[0].elements[i].value); var FormName = document.forms[0].elements[i].name; var TstEmail = EmailTest.test(FormName); if (TstEmail){ValidateEmail();} if(!found) { alert('The "' +FormName+ '" field is required.|n Please enter your '+FormName); document.forms[0].elements[i].focus(); return false; } }
function ValidateEmail() { var format=/^[^@]+@([-\w]+\.)+[A-Za-z]{2,4}$/; if(found.search(format) == -1){ alert("Your Email Address " +found+ " is not formatted correctly."); document.forms[0].elements[i].focus(); return false; } } }
<Input type=SUBMIT onclick='return ValidateAll(this.form);'> -------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------- |
|
Comments (2) | Leave Comment | Link
|