4

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.

7
  • 1
    Welcome to Stack Overflow! What have you tried? Commented Jun 26, 2012 at 14:59
  • 1
    possible duplicate of Get ID from URL with jQuery Commented Jun 26, 2012 at 14:59
  • 1
    @Esailija: Except this isn't flagged with 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. Commented Jun 26, 2012 at 15:04
  • 1
    @Esailija: No, I'm not: This answer is precisely useless if the OP isn't using jQuery, just as the accepted answer is useless for this questioner (as it relies on the number being the last thing in the URL). Commented Jun 26, 2012 at 15:13
  • 1
    @Esailija: We just disagree. :-) (I didn't call it a "crime" -- that would have been way overstating it if I had.) Commented Jun 26, 2012 at 16:21

2 Answers 2

12

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
Sign up to request clarification or add additional context in comments.

2 Comments

This 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; }
Foe this example, you can use this location.search.replace('?id=', '')[1]
5

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).

2 Comments

Could you please elaborate on what the m[1] guard is for? I think it is redundant with the + quantifier.
@pimvdb: It was indeed, thank you. Doh! I do tend to be a belt-and-braces guy, but that was OTT. :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.