How do you get a part of a URL hash using js?
Here is what I have:
something.html?il=#/new/product/123
And I need to get "123" as a variable ...
***no libraries, pure javascript please.
Any ideas?
How do you get a part of a URL hash using js?
Here is what I have:
something.html?il=#/new/product/123
And I need to get "123" as a variable ...
***no libraries, pure javascript please.
Any ideas?
you need the hash, not the querystring. Anything after the # is called the hash of the url.
You can use document.location.hash and parse that string
var id = document.location.hash.split("/"); //convert the hash into an array, splitting with "/"
id = id.pop(); //pop will get the last item on the array
However readable and easy this method is, its not safe to assume the string you are searching will always be the last on the array. You could use a regular expression to further narrow the chances
var hash = document.location.hash,
re = /\/new\/product\/(d+)/,
id = hash.match(re);// for some reason this matches both the full string and the number
id = id.pop(); // so I must do this again
Here is some Javascript that should help you. Just take the return value from the getQuerystringNameValue() function and use $("#textboxID").val(returnValue); to assign it to the textbox.
alert("name1" + " = " + getQuerystringNameValue("name1"));
alert("name2" + " = " + getQuerystringNameValue("name2"));
alert("name3" + " = " + getQuerystringNameValue("name3"));
function getQuerystringNameValue(name)
{
// For example... passing a name parameter of "name1" will return a value of "100", etc.
// page.htm?name1=100&name2=101&name3=102
var winURL = window.location.href;
var queryStringArray = winURL.split("?");
var queryStringParamArray = queryStringArray[1].split("&");
var nameValue = null;
for ( var i=0; i<queryStringParamArray.length; i++ )
{
queryStringNameValueArray = queryStringParamArray[i].split("=");
if ( name == queryStringNameValueArray[0] )
{
nameValue = queryStringNameValueArray[1];
}
}
return nameValue;
}
In JavaScript, document.location.search
contains the query parameters. You can use Regular Expressions to parse out the pieces you need. However, in the URL in your example, it isn't the query string, it's the anchor, found in document.location.hash
.