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
Advertisement
Answer
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.