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?
The URLSearchParams interface defines utility methods to work with the query string of a URL.
URLSearchParams is a representation of the parsed search params. Parsing (specified here) includes decoding the values.
Query parameters are a defined set of parameters attached to the end of a url. They are extensions of the URL that are used to help define specific content or actions based on the data being passed. To append query params to the end of a URL, a '? ' Is added followed immediately by a query parameter.
Method 1: Using the URLSearchParams Object The URLSearchParams is an interface used to provide methods that can be used to work with an URL. The URL string is first separated to get only the parameters portion of the URL. The split() method is used on the given URL with the “?” separator.
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.
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] = val;
return a;
}, this.params);
}
get(key) {
return this.params[key];
}
}
const params = new UrlParams('?q=Javascript+Stuff');
console.log(params.get('q'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With