Extract query string from local a href - javascript

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?

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/

Related

How to ignore invalid URL parameters?

Before I go on, let me say that I've looked through a number of threads already and can't find an answer that works for me.
Basically, I've built a custom link shortener and I'm using URLSearchParams to pull the URL to be shortened and the custom slug from the URL search query as follows:
var e = window.location.search;
const urlParams = new URLSearchParams(e);
const url = urlParams.get("url");
const slug = urlParams.get("slug");
Where the format for a query is: ?url=https://google.com&slug=customslug
After the parameters are handled, the URL string is treated with trim() to remove any whitespace. The final output is encoded with encodeURIComponent() when the API I'm using (https://short.io) is called.
However, I want to be able to pass URLs with &, like so: ?url=https://google.com/&testing&slug=customslug. My ideal solution would simply treat any & that isn't part of the &slug parameter as a part of the URL contained within the &url parameter. Currently, the & character is ignored if it isn't attached to a valid parameter (url or slug).
I have tried encoding the query input using encodeURIComponent(), but that results in a failure to pick up on either defined parameter. I have also tried splitting the input using split("&slug",1), but that results in an array and I cannot pass arrays to the Short.io API.
Any suggestions?
You should use the URL Encoded ampersand symbol %26.
var e = "?url=https://google.com/%26testing&slug=customslug";
const urlParams = new URLSearchParams(e);
const url = urlParams.get("url");
const slug = urlParams.get("slug");
console.log(url);
console.log(slug);
I solved my issue by building off of #CherryDT's comment about using window.location.hash to get my URL string. Ultimately, I chose to forgo the idea of a slug in the address bar, since it would cause further problems with my script.
While this solution is only applicable for my purposes, I'm detailing the solution because it functions as a workaround for the issue of not being able to encode a passed URL string from the address bar. Might be useful to someone, someday.
var e = window.location.href.replace(window.location.hash, '');
if (e.endsWith("?") === true) {
var url = window.location.hash.substr(1);
if (url === "") {
// Error code
} else {
console.log("A URL to be shortened was provided via hash.");
// Pass url to rest of script
}
}

How can I insert dynamic value to URL in cy.visit()?

I am trying to insert value to URL which I want to visit. I use this (for example):
const idp = '10'
cy.visit('http://test.com/aaa/bbb?id=${idp}')
but when I run this, it will ends on this http://test.com/aaa/bbb?id=$%7Bidp%7D
instead of id=10.
Also I am interested how can I get value from URL to variable.
For example I have URL http://test.com/aaa/bbb?id=5 and I want to create variable idc which will have value 5.
I think you are using the wrong quotes, you need to use backticks to use Template Literals:
cy.visit(`http://test.com/aaa/bbb?id=${idp}`)
You can then use cy.url() to get the current URL as a string and use JavaScript to parse the string as normal.
For the first part of your question you need to use backticks(also called grave accents) as outlined in the Template Literals docs instead of regular quotes. Your line would then look like -
cy.visit(`http://test.com/aaa/bbb?id=${idp}`)
For the second part of your question, you can use URLSearchParams (Note this DOES NOT work in IE). An example would be -
var url = new URL("http://test.com/aaa/bbb?id=5");
var searchParams = new URLSearchParams(url.search);
const urlParams = new URLSearchParams(searchParams );
const myParam = urlParams .get('id');

Get background image url value

I am trying to get the value of the backgound-image url. The url is set inline directly in the element tag with the style attribute like so
<a style="background-image: url(https:// ....)"></a>
I tried doing
var url = $(this).css('background-image')
with various regexes but it does not seem to work. I am trying to store this URL into MongoDB but I get this error
var styles = parse(el.attribs.style);
TypeError: Cannot read property 'attribs' of undefined
Get the style value, then strip the URL from it
var bi = $('a').css("background-image");
alert(bi.split(/"/)[1]);
The call to jQuery .css("background-image") always returns the URL within double quotes, regardless how it was set originally.
Sample fiddle:
https://jsfiddle.net/6qk3ufcb/
In vanilla JS, having full DOM access, it can be done like so:
document.querySelector('a').style.backgroundImage.split('"')[1]
Or, if for whatever reason you don't have DOM access (for example dealing in node, and operating on some simplified HTML parser) it can also be done with regexp:
const htmlString = `<div class="bg-div" style="background-image: url('https://loremipsum.com/imageIpsum.jpg');">`
const reg = /url.'([\w\W]+?)'/;
const searched = reg.exec(htmlString)
console.log(searched[1]) //=> https://loremipsum.com/imageIpsum.jpg

Change the pathname in the URL of a link while keeping the querystring constant

From a page with the following URL, http://example.com/foo.html?query=1&other=2, I want to create a link to http://example.com/bar.html?query=1&other=2. How do I do that without explicitly saving and reloading all the query strings.
I need this to easily link from an iframe version of a page (embed.html?query) to the full page (index.html?query).
I would have recommended using the Location object's search method (available at document.location or window.location) to pull out the parameters, then modify the rest of the URL, but that API is apparently specific to Firefox.
I would simplify #DMortensen's answer by just splitting on the first ?, then modifying the first part (which will be the URL's path portion only), and reapplying the second part.
If you need to parse the parameters, I recommend the jQuery plugin Query Parameter Parser: one call to $.parseQuery(s) will pull out an object of all the keys & values.
It can be finicky, but you could split the URI on '?' and then loop through the 2nd element of that array to grab the key/val pairs if you need to evaluate each pair (using '&' as a delimiter). The obvious weakness in this would be if there are additional '?' or '&' used in the URI.
Something like this maybe? (pseudocode-ish)
var URI = document.URL;
var qs = URI.split('?');
var keyvalpair = qs[1].split('&');
var reconstructedURI = '&' + keyvalpair;
for(var i = 0; i< keyvalpair.length; i++){
var key = keyvalpair[i].split('=')[0];
var val = keyvalpair[i].split('=')[1];
}
Thank you for all the answers. I tried the following and it works.
function gotoFullSite() {
var search = window.location.search;
window.open("http://example.com/"+search)
}
$('#clickable').click(gotoFullSite);
and then use <a id = "clickable" href="#"></a>. When I click the link, it opens the proper website with all the query parameters in a new tab. (I need a new tab to break out of an iframe.)

converting request.querystring using toString()

In JScript, why do I get the error "Object doesn't support this property or method" when I try to convert request.querystring to a string using toString()?
var params = Request.QueryString;
var params = params.toString();
Background info:
I'm trying to convert the querystring to a string so that I can perform a regex replace and remove certain items when they appear in the url.
var param = param.replace(/([?&])(allow)=[\w-]+/g, "");
I recently discovered the solution to this problem.
var params = Request.QueryString;
should be:
var params = Request.QueryString.Item;
There is no need to convert params to a string after that to manipulate the query string. Further you have access to everything in the query string by calling Request.QueryString("param").Item.
Example:
http://www.mysite.com?q=query&name=george
var name = Request.QueryString("name").Item;
I don't know -- weird Microsoft JScript implementation.
I had the same problem.
var strParams = new String(params);
seems to work though.

Categories