Sometimes, we want to Get the ID from URL with JavaScript.
In this article, we’ll look at how to Get the ID from URL with JavaScript.
Get the ID from URL with JavaScript
To Get the ID from URL with JavaScript, we can call the JavaScript string’s split
method on the URL string.
Then we get the last part of it with the JavaScript array at
method.
For instance, we write:
const url = "http://www.site.com/234234234"
const strs = url.split('/');
const id = strs.at(-1)
console.log(id)
We call split
with '/'
to split the url
string by the /
.
Then we call at
with -1 to get the element from the strs
array.
Therefore, id
is 234234234
as we expect.
Conclusion
To Get the ID from URL with JavaScript, we can call the JavaScript string’s split
method on the URL string.
Then we get the last part of it with the JavaScript array at
method.