I`m new to JavaScript and I need some help extracting the ID from URL using JavaScript for a gallery.
This is the link: www.shinylook.ro/produs/44/mocasini-barbati.html
.
I need that number 44 in a variable.
I`m new to JavaScript and I need some help extracting the ID from URL using JavaScript for a gallery.
This is the link: www.shinylook.ro/produs/44/mocasini-barbati.html
.
I need that number 44 in a variable.
You have to use the location
object to get the URL, after that, you can use split
to split the URL on the slashes.
location.pathname.split('/')[2] // Returns 44 in your example
You can do that with String#split
or with a regular expression.
String#split
lets you split a string on a delimiter and get an array as a result. So in your case, you could split on /
and get an array where 44
would be at index 2.
Regular expressions let you do much more complicated matching and extraction, as shown by the various demos on the linked page. For instance,
var str = "www.shinylook.ro/produs/44/mocasini-barbati.html";
var m = /produs\/(\d+)\//.exec(str);
if (m) {
// m[1] has the number (as a string)
}
In both cases, the number will be a string. You can parse it with parseInt
, e.g. n = parseInt(s, 10)
(assuming it's base 10).