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?
CodePudding user response:
You should use the URL Encoded ampersand symbol &
.
var e = "?url=https://google.com/&testing&slug=customslug";
const urlParams = new URLSearchParams(e);
const url = urlParams.get("url");
const slug = urlParams.get("slug");
console.log(url);
console.log(slug);
CodePudding user response:
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
}
}