1

How can I parse a link in jqueryjavascript?

I have the url (some path)/restaurantProfile.php?id=51

And I want to parse this to only obtain the 51. (keep in mind this needs to be generalized. The id won't obviously be always 51...)

Thanks in advance!

FailedUnitTest
  • 1,637
  • 3
  • 20
  • 43
Tirafesi
  • 1,297
  • 2
  • 18
  • 36

4 Answers4

1

You can split the string at id=:

var url = 'some/path/restaurantProfile.php?id=51';
var id = url.split('id=')[1]; // 51
adrice727
  • 1,482
  • 12
  • 17
1

I forget where I saw this, but here is a nice jquery function you can use for this:

//jQuery extension below allows for easy query-param lookup
(function($) {
    $.QueryString = (function(a) {
        if (a == "") return {};
        var b = {};
        for (var i = 0; i < a.length; ++i)
        {
            var p=a[i].split('=', 2);
            if (p.length != 2) continue;
            b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
        }
        return b;
    })(window.location.search.substr(1).split('&'))
})(jQuery);

Usage like so:

var restaurantId =  $.QueryString["id"];
FailedUnitTest
  • 1,637
  • 3
  • 20
  • 43
0
  1. You can make use of Regular Expression in javascript. RegExp Object provides methods to Match the Regular Expression with a input String.

  2. You can make use of string object split method to split the string by using a separator character.

There is a similar question at How can I get query string values in JavaScript? for more options.

Community
  • 1
  • 1
Abhinav Galodha
  • 9,293
  • 2
  • 31
  • 41
0

You can use the URLSearchParams API to work with the query string of a URL

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams

// get the current url from the browser
var x = new URLSearchParams(window.location.search);

// get the id query param
var id = x.get('id');
manonthemat
  • 6,101
  • 1
  • 24
  • 49