[thelist] Testing URL with regular expression

Kowalkowski, Lee (ASPIRE) lee.kowalkowski at hmrcaspire.com
Thu Oct 13 09:57:06 CDT 2005


> -----Original Message-----
> From: thelist-bounces at lists.evolt.org
> [mailto:thelist-bounces at lists.evolt.org]On Behalf Of Gardiner, Iain
> Sent: Thursday, October 13, 2005 10:57 AM
> To: 'thelist at lists.evolt.org'
> Subject: [thelist] Testing URL with regular expression
> 
> Basically,  I want to check the window.location against the 
> href element of
> a link but it's important that it can match if the filename 
> and/or anchors
> are included.  So I've arrived at this expression:
>  
>     urlRegEx = /(index.php)?(#{1}.*)?/;
>  
> And I use this conditional:
>  
>     if (navigationLink.href == window.location + urlRegEx)
>  
> Hopefully this will match all of these eventualities:
>  
>     URL/
>     URL/index.php
>     URL/#anchor
>     URL/index.php#anchor
>  

Good try!  Can't quite do it that way, if you want to match the URL, the URL
must be part of the regex, you cannot append your regex object to a string
like that.  With your href in your regex you probably want to make sure the
dots in your host name aren't treated as special characters by escaping
them:

var urlRegEx = new RegExp("^" + location.href.replace('.','\\.') +
"/(index\\.php)?(#.*)?$");
if(urlRegEx.test(navigationLink.href))
{
	// valid
}
else
{
	// invalid
}

... could the slash be absent?  May need tweaking if so :
"(/index\\.php(#.*)?)?(/#.*)?$"

There's no need to have "{1}" in a regular expression.  You need to use the
"^" and "$" characters to match the entire string, otherwise it would match
any URL with the current location in parameter values and also not be
limited to index.php or anchors, e.g. URL/anything would match.

- LK


===========================================================
Our e-mail domain has now changed from iraspire.com to hmrcaspire.com. Please update your address books.
===========================================================



More information about the thelist mailing list