...

View Full Version : RegExp Question



Basscyst
07-11-2004, 11:51 PM
In the following regExp:



function regExp(val)
{
var str=/^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

var test=val.search(str);
if(test==-1)
{
alert();
}

}


What exactly is the \1 doing? Judging by the functionality it seems to be referencing the found character in (\-|\/|\.) Is that correct? If so care to elaborate a bit?

Thanks,
Basscyst

dumpfi
07-12-2004, 01:18 AM
What exactly is the \1 doing? Judging by the functionality it seems to be referencing the found character in (\-|\/|\.) Is that correct? If so care to elaborate a bit?

Thanks,
BasscystExactly, it is referencing the found character. ( \1 references to the first characters enclosed in (), \2 would reference to the second ones, etc.). Up to 9 parenthesis per expression are allowed if i'm not mistaken. You can reference later in the script to the enclosed pieces, too, by using RegExp.$1, RegExp.$2, etc.

It seems the RegExp you posted trys to find out, if the string is date-like.

First it searchs for 1 or 2 numbers, then for a . or a / or a -. Then for another 1 or 2 numbers. After this it looks for . or / or - (the one which matched before) and for another 4 numbers.

Example strings that would match:
12.07.2004
12/7/2004
12-07-2004

Strings that would not match:
12.07/2004
12-07-04
12/7-2004
12. 07. 2004
some blah 12/07/2004 some blah

dumpfi

Basscyst
07-12-2004, 01:33 AM
Thanks Dumpfi nice explanation,

It is a date validation script. That's the one from the tutorial, but I thought it would be nice to be able to have any non alphanumeric character as the delimiter so I came up with this:



<script type="text/javascript">

function dateValid(frm)
{

var str=frm.replace(/\W/g, "/");
var cut=str.split('/');
var dt=new Date(str);
var mt=dt.getMonth()+1;
if(cut[0]!=mt)
{
alert("Please Enter A Valid Date");
}
else
{

chk2=str.search(/^\d{1,2}\/\d{1,2}\/\d{4}/)

if(chk2==-1)
{
alert("Please Provide A Valid Date!");
}
else
{
alert("The Date Is Right!")
}
}
}
</script>


I think it's kinda cool for my first use of RegExp.

Basscyst



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum