Javascript prevent redundancy when joining multiple arrays
replace
only works on the first found item in the string. You can either use replaceAll
, or split
and join
, which is more cross-browser friendly as below:
function cleanLink(link) {
let newLink = link.split('&&').join('&'); // remove duplicate ampersands
if (newLink[0] === '&') {
newLink = newLink.slice(1); // remove starting ampersand
}
if (newLink[newLink.length - 1] === '&') {
newLink = newLink.slice(0,-1); // remove trailing ampersand
}
return newLink;
}