How to get the whole URL with parameters?

I need to get the whole URL with parameters as a string. For example, I need to get the following URL:

http://www.keytometals.com/page.aspx?ID=CheckArticle&site=kts&LN=EN&NM=349 

I tried to use:

 document.location.href, document.URL, window.location.href 

but it only retrieves part of the url:

 http://www.keytometals.com/page.aspx 

How to get a string containing the current URL, as well as its parameters?

One update: I used

 window.content.document.location.href 

and I have the following URL:

 http://www.keytometals.com/page.aspx?ID=CheckArticle 

Unfortunately, it is still part of the URL. Can someone help me how to get the whole url as a string?

Thanks!

+6
source share
3 answers

You just need to just document.location - this will include everything. Will you need to write your own code to split it into? to get only the query string and then split this into name / value pairs on each &.

EDIT:

Actually, you can use location.search . Here is the snippet I wrote for this:

 function loadQueryString(){ var parameters = {}; var searchString = location.search.substr(1); var pairs = searchString.split("&"); var parts; for(i = 0; i < pairs.length; i++){ parts = pairs[i].split("="); var name = parts[0]; var data = decodeURI(parts[1]); parameters[name] = data; } return parameters; } params = loadQueryString(); 
+3
source

You should use window.location.href for the entire URL (including the query string).

See the Mozilla documentation for more information and other properties.

Here is another good StackOverflow article on how to query parsing string in JavaScript .

+2
source
 function getQueryString() { var key = false, res = {}, itm = null; // get the query string without the ? var qs = location.search.substring(1); // check for the key as an argument if (arguments.length > 0 && arguments[0].length > 1) key = arguments[0]; // make a regex pattern to grab key/value var pattern = /([^&=]+)=([^&]*)/g; // loop the items in the query string, either // find a match to the argument, or build an object // with key/value pairs while (itm = pattern.exec(qs)) { if (key !== false && decodeURIComponent(itm[1]) === key) return decodeURIComponent(itm[2]); else if (key === false) res[decodeURIComponent(itm[1])] = decodeURIComponent(itm[2]); } return key === false ? res : null; } 

Then you use it as follows:

 // get a single key (if it exists) var t = getQueryString('site'); console.log(t); // get the whole thing as an object t = getQueryString(); console.log(t); 
0
source

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


All Articles