Wednesday, February 07, 2007

Javascript: matching with regex

There seem to be 3 ways to use regular expressions in javascript:
1.
var val = document.getElementById("some_id").value;
val.replace(/^\s+|\s+$/g, ""); //trim using regex
2.
var alpha = /^[A-Za-z]+$/ ;
var val = document.getElementById("some_id").value;
if(alpha.test(val)){
//val matches alpha
}
3.
var val = document.getElementById("some_id").value;
var alpha ='((?:[a-z][a-z]+))'; // Word 1
var p = new RegExp(alpha,["i"]);
var m = p.exec(val);
if (m.length>0)
{
var word=m[1];
//word is the capture group 1
}
if anyone knows a better way, feel free to share.

No comments:

Post a Comment