Home > Back-end >  Is possible to get the last string of an url as a param?
Is possible to get the last string of an url as a param?

Time:02-12

I cant get it with javascript URLSearchParams function because it needs the "?" before.

Its possible to get the last string after last slash of an URL?

For ex: 
mydomain.com/hello
mydomain.com/otherExample

I need that "hello" be the param and stay in the index of my domain with the "param" value assigned to a var? Note that the "hello" page or directory doesn't exists.

Maybe is possible to manage it with the 404 error redirection?

CodePudding user response:

You should be able to retrieve it with the following Javascript:

let parts = window.location.pathname.split('/');
let path = parts[parts.length - 1];

CodePudding user response:

The Location object has a property that does exactly what you want:

window.location.pathname

If you don't want the initial slash, you can remove it like so:

window.location.pathname.substring(1)

Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Location

  • Related