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.
Share Improve this question edited Jun 26, 2012 at 15:06 pimvdb 155k80 gold badges311 silver badges356 bronze badges asked Jun 26, 2012 at 14:57 user1483138user1483138 671 gold badge1 silver badge7 bronze badges 7 | Show 2 more comments2 Answers
Reset to default 12You 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).
jquery
, and the number isn't at the end of the URL. Many of the answers there rely on one or the other of those. – T.J. Crowder Commented Jun 26, 2012 at 15:04