JavaScript query string

Using document.referrer, we get the entire URL link in JavaScript, for example:

http://localhost/testwordpress/wp-admin/admin.php?page=thesis-options&upgraded=true

From this output, how can we extract only part of the query string:

?page=thesis-options&upgraded=true

Is there any method in JavaScript?

+3
source share
3 answers

If you just want to get the values ​​from the query string, I use the following function:

function getQuerystring(key)
{
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(window.location.href);
  if(qs == null)
    return default_;
  else
    return qs[1];
}

Just go through the key you are looking for and return the value. IE: getQueryString ('upgradeed') will return true

+1
source

To get the query string from document.referrer, you can use split():

var qs = document.referrer.split('?')[1];

if (typeof qs !== 'undefined') {
    // qs contains the query string.
    // this would be "page=thesis-options&upgraded=true" in your case.
}
else {
    // there was no query string in document.referrer.
}
+4
source

. . , .

0

Source: https://habr.com/ru/post/1540732/


All Articles