user10791031
user10791031

Reputation:

Jquery: get query value from beatified url

Is there any way to get the id from a beautified URL? I have a beautified an URL with .htaccess:

Old URL: https://example.com/products.php?id=UDn4LdBa3yy

new URL: https://example.com/product/UDn4LdBa3yy

Now I need to get the id form the URL with javascript. But a standard javascript function to split the URL at the = doesn't work anymore.

Upvotes: 0

Views: 38

Answers (1)

Arjun Sethi
Arjun Sethi

Reputation: 36

Just extract last part of url after "/" using subString() in javascript. If there is another query string that follows, include the index of the '?' character, otherwise omit the index. See below:

var newURL="https://example.com/product/UDn4LdBa3yy";
var queryString=newURL.indexOf('?');
var id;
if(queryString!=-1){
    id=newURL.substring(newURL.lastIndexOf('/')+1,queryString);
}
else{
    id=newURL.substring(newURL.lastIndexOf('/')+1);
}
console.log(id);

Upvotes: 1

Related Questions