I have this project in which I create a link with multiple arrays that are joined with & signs. It works perfectly, but when I get more than 3 arrays, it doesn't. When I skip a couple of questions I get a & sign at the beginning of the string and when I only choose the first it adds one to the end which is bad. Also if I choose the first and the last array and skip the rest there a multiple & added between while I always just want 1.
I use this to join the arrays:
/**
* Returns the parameters for the URL.
*
* @returns {string}
*/
getLink() {
this.tmp = [];
for (let i = 0; i < this.url.length; i ) {
// Check if question is from the same quiz part and adds a , between chosen answers and add the right prefix at the beginning
if (this.url[i].length > 0) {
this.tmp.push("" Quiz[i].prefix this.url[i].join(","))
}
// if the link is empty remove everything that was added (& an ,)
if (this.url[i].length === 0) {
this.tmp.push("");
}
}
/// If answers are from different quiz parts add a & between answers
return "" this.tmp.join("&");
}
Quiz and this.url are the arrays and .prefix and stuff are keys of the arrays.
This is what I use to check the link string to remove the unwanted & signs:
LinkChecker(link) {
let cleanLink = link.split('&&').join('&');
if (cleanLink[0] === '&') {
cleanLink = cleanLink.slice(1);
}
if (cleanLink[cleanLink.length - 1] === '&') {
cleanLink = cleanLink.slice(0, -1);
}
return cleanLink;
console.log(cleanLink.length)
}
And this is something I tried now:
let i = 0;
let LastLink = '';
let FirstLink = LastLink;
let link = this.LinkChecker(this.getLink());
if (link[link.length -1] === '&'){
LastLink = link.slice(0, -1);
}
while(i == '&'){
if(LastLink[i] === '&'){
FirstLink = link.slice(-1, 0);
}
i
}
console.log(FirstLink)
But it also doesn't really work.
Preview:
bd_shoe_size_ids=6621&&&
&&manufacturer_ids=5866
bd_shoe_size_ids=6598&&&manufacturer_ids=5866
It's supposed to look like:
bd_shoe_size_ids=6598&manufacturer_ids=5866
CodePudding user response:
It is better to avoid than to fix (the double &
).
Remove the whole block that does push("")
. This push is adding an entry to your array that you really don't want to have at all, so just don't push it.
CodePudding user response:
Your LinkChecker
method only considers pairs of &
s. You can handle any number of &
s by splitting and filtering out any empty entries in the array:
LinkChecker(link) {
// split by & and then filter out the blank entries
let cleanLink = link
.split('&')
.filter((section) => section !== '') // remove any empty strings
.join('&');
if (cleanLink[0] === '&') {
cleanLink = cleanLink.slice(1);
}
if (cleanLink[cleanLink.length - 1] === '&') {
cleanLink = cleanLink.slice(0, -1);
}
return cleanLink;
console.log(cleanLink.length)
}
As others have mentioned, there are ways to solve this in your array creation but since your LinkChecker seems to be where you are cleaning them specifically, I only changed that method for the sake of clarity.