0

the url: http://site/page?object_id=2 I want the number (id).

4
  • 3
    Is the given URL the URL of the current document? Commented Feb 24, 2010 at 18:50
  • current doc? I want the id in the URL. Commented Feb 24, 2010 at 18:52
  • I think Gumbo understands what you want, but how you get it can be different depending on the context. Unless we're on a "need to know" basis, and the context that the js is running in is classified... Commented Feb 24, 2010 at 18:56
  • 1
    The point is, if you've got a Location object such as window.location or any of the a element nodes, you can use obj.search to get the query string without having to use dodgy regexes that will fail if the URL is in an unexpected form. You should also consider using a proper query string parser that breaks on both & and the alternative ; and does decodeURIComponent on the name and value, if the URL can be in any form. Commented Feb 24, 2010 at 19:41

4 Answers 4

3

Try the following:

/\?(?:.*?&)?object_id=(\d+)/.exec(url)[1]

Unlike other answers, this will correctly handle http://site/page?other_object_id=3&object_id=2

Sign up to request clarification or add additional context in comments.

Comments

2

If you have the URL in a string:

var str = "http://site/page?other_object_id=10&object_id=2";
var match = str.match(/[?&]object_id=(\d+)/);

if (match) {
  alert(match[1]); // 2
}

If it's the URL of the current page:

var match = location.search.match(/[?&]object_id=(\d+)/);

if (match) {
  alert(match[1]);
}

1 Comment

Unless the path contains an &.
2

Try this:

var url = 'http://site/page?object_id=2';
var object_id = url.match(/object_id=(\d+)/)[1];

1 Comment

I would just take the $ away, your \d+ should work fine. Also put the + inside the parentheses - (\d+).
1
foo.match(/(\d+)/);

Comments

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.