Melab
Melab

Reputation: 2822

URLSearchParams does not return the same string as found in a URL's parameters

This is in Chrome at least. If my window's URL is https://www.google.com/search?q=JavaScript+URLSearchParams and I run this in the JavaScript console:

url = new URL(document.URL);
urlsp = url.searchParams;
console.log(urlsp.get("q"));

then what gets logged to the console is not JavaScript+URLSearchParams, but JavaScript URLSearchParams. This is a pain because the userscript that I am trying to write needs access to the actual value of the q parameter; and + are not treated the same by the browser. Sure, I could write some code that would process the URL as a string, but that would be tedious and error-prone. The same deal happens with the value %3A in a parameter, but it gets returned as : instead. How do I get URLSearchParams to return the actual value of a URL's parameter?

Upvotes: 28

Views: 72618

Answers (4)

thomasmeadows
thomasmeadows

Reputation: 1881

    url = new URL(document.URL);
    urlsp = url.searchParams;
    console.log(encodeURI(urlsp.get("q")));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI

Upvotes: 5

Dlovan
Dlovan

Reputation: 11

try this it will work!. test url http://localhost/?invitationCode=2hks7923

 var params = new window.URLSearchParams(window.location.search);
     console.log(params.get('invitationCode'))

Upvotes: 1

Rob M.
Rob M.

Reputation: 36511

I could write some code that would process the URL as a string, but that would be tedious and error-prone

I don't know about that, this is a fairly new API and we've been surviving ok without for a long time. There are problems with it anyway, last I checked the API doesn't support parameter arrays like foo[]=1&foo[]=2. It really isn't very complicated and it's not that much code to just roll your own:

class UrlParams {
   constructor(search) {
      this.qs = (search || location.search).substr(1);
      this.params = {};
      this.parseQuerstring();
   }
   parseQuerstring() {
      this.qs.split('&').reduce((a, b) => {
        let [key, val] = b.split('=');
        a[key] = decodeURIComponent(val).replaceAll('+', ' ');
        return a;
      }, this.params);
   }
   get(key) {
      return this.params[key];
   }
}

const params = new UrlParams('?q=Javascript+Stuff');
console.log(params.get('q'));

Upvotes: 9

Domenic
Domenic

Reputation: 112827

URLSearchParams is a representation of the parsed search params. Parsing (specified here) includes decoding the values.

If you don't want to parse the search params, but instead just e.g. split on ampersands and = signs, then don't use url.searchParams. Use instead url.search, and perform the splitting yourself.

Upvotes: 30

Related Questions