Reputation: 277
I'm writing a tweak script / extension to an existing website. There is a <a href
that points to a local file (like <a href='/thing.php?id=123§ion=456'>
) I want to extract the id, 123
in that case. Currently it does $('#theID').attr('href').split('&')[0].split('=')[1]);
which is cursed.
However, I cannot do new URL($('#theID').attr('href')).searchParams.get('id')
because I get Uncaught TypeError: URL constructor: /thing.php?id=123§ion=456 is not a valid URL.
How can I properly parse this?
Upvotes: 0
Views: 86
Reputation: 4443
Since you are retrieving the URL from an anchor tag, you can use its properties. The query string can be retrieved from the search
property. Then you can manually parse the query string or use the new URLSearchParams
feature to parse it.
For example:
var a = document.getElementById("test");
var search = a.search;
var parsed = new URLSearchParams(search);
var q = parsed.get("q");
alert(q);
https://jsfiddle.net/uwo2a17p/
Upvotes: 1