Categories
JavaScript Answers

How to Get the ID from URL with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *