0

I want to query the parameters in the URL using query.

Let's say if my vistiors open the url example.com/#o-12345

Here #o is the identifier/parameter and 12345 is the ID.

How can I use jQuery to check if the particular parameter is present in the URL and how to extract the ID?

Nirmal Kumar
  • 139
  • 2
  • 7

1 Answers1

0

Here I wrote a parser, that stores all your parameters into an object:

let params = {};
let splittedUrl = window.location.href.split('#');
if (splittedUrl.length >= 1) {
  splittedUrl[1].split('&').forEach(elm => {
    if (elm != '') {
      let spl = elm.split('-');
      params[spl[0]] = (spl.length >= 2 ? spl[1] : true);
    }
  });
}

(This code will also let you add more parameters with an ampercent sign.)

Example (with the URL 'https://example.com/#foo-bar&tmp-qux'):

Object.keys(params).length // 2
params['foo'] // bar
params['tmp'] // qux

I know, you asked for jQuery, but I think pure JavaScript should also work :)

garzj
  • 2,427
  • 2
  • 8
  • 15