lurf jurv
lurf jurv

Reputation: 277

Extract query string from local a href

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&section=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&section=456 is not a valid URL. How can I properly parse this?

Upvotes: 0

Views: 86

Answers (1)

Jack A.
Jack A.

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

Related Questions