Monday, May 18, 2009

Decoding URI/URL strings

In one of my last post, I talking about Finding the Url paramters from a URL using javascript.

But there is a problem with the code, what if the url has some HTML encoding inside like %20 (which represents a space) or some other special html encoding.

You will need to use decodeURI function in javascript. The function will decode html special charecters to their correct form so things like Hello%20World will become Hello World.

[source lang='jscript']
function gup( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return decodeURI(results[1]);
}
[/source]

No comments:

Post a Comment