[thelist] Testing URL with regular expression

Iain iain at firelightning.com
Thu Oct 13 12:05:50 CDT 2005


Hi Lee,

Great answer, thanks.  You set me on the right track, but I'd got myself confused and had the way I needed to check things back to front.  Here's the full function I've arrived at that works *exactly* as I wanted:

	setCurrent: function()
	{
		// Local variables for this function:
		var navigationLink, currentLinkText, urlRegEx, i;

		for (i = 0; i < setCurrentNavigation.navigationItems.length; i++)
		{
			navigationLink = setCurrentNavigation.navigationItems[i].getElementsByTagName('a')[0];
			// Define test accounting for both filename and anchor extensions to the URL:
			urlRegEx = new RegExp("^" + navigationLink.href.replace('.', '\\.') + "(index\\.php)?(#.*)?$");

			// Test the current page address matches the navigation link:
			if (urlRegEx.test(window.location))
			{
				// Move the link text into the list item:
				currentLinkText = document.createTextNode(navigationLink.firstChild.nodeValue);
				setCurrentNavigation.navigationItems[i].appendChild(currentLinkText);
				// Remove the redundant link and set the list item's ID:
				setCurrentNavigation.navigationItems[i].removeChild(navigationLink);
				setCurrentNavigation.navigationItems[i].id = 'current';
			}
		}
	}

Thanks again,

Iain

Kowalkowski, Lee (ASPIRE) wrote:
> 
> 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