0

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.

  • 1
    Please refer the below article https://stackoverflow.com/questions/4758103/last-segment-of-url – Sanyam May 13 '20 at 18:41
  • @Sanyam That wouldn't work if the user puts something in the URL or when I have another query string in the URL –  May 13 '20 at 18:43

1 Answers1

1

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);
  • If this would not fit one of your use cases, provide an example of when it would not and I can edit the answer. – Arjun Sethi May 13 '20 at 18:52