Getting ID from URL using JavaScript
Solution 1
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
Solution 2
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).
user1483138
Updated on June 05, 2022Comments
-
user1483138 almost 2 years
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.
-
pimvdb almost 12 yearsCould you please elaborate on what the
m[1]
guard is for? I think it is redundant with the+
quantifier. -
T.J. Crowder almost 12 years@pimvdb: It was indeed, thank you. Doh! I do tend to be a belt-and-braces guy, but that was OTT. :-)
-
user1483138 almost 12 yearsThis is what i had for this kind of link shinylook.ro/product.php?id=44 function transferaId() { var v = {}; var foo = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, cheie, val) { v[cheie] = val; }); return v; }
-
Calvein almost 12 yearsFoe this example, you can use this
location.search.replace('?id=', '')[1]