Tengo este proyecto en el que creo un enlace con varias matrices que se unen con & signos. Funciona perfectamente, pero cuando obtengo más de 3 matrices, no funciona. Cuando omito un par de preguntas, obtengo un signo & al comienzo de la cadena y cuando solo elijo la primera, agrega una al final, lo cual es malo. Además, si elijo la primera y la última matriz y omito el resto, hay un múltiplo y agregado entre mientras que siempre solo quiero 1.
Yo uso esto para unir las matrices:
/** * 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 y this.url son las matrices y .prefix y demás son claves de las matrices.
Esto es lo que uso para verificar la cadena de enlace para eliminar los signos & no deseados:
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) }Y esto es algo que probé ahora:
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)Pero tampoco funciona realmente.
Avance:
bd_shoe_size_ids=6621&&&
&&fabricante_ids=5866
bd_shoe_size_ids=6598&&&fabricante_ids=5866
Se supone que debe verse como:
bd_shoe_size_ids=6598&fabricante_ids=5866
Su método LinkChecker solo considera pares de & s. Puede manejar cualquier número de & s dividiendo y filtrando las entradas vacías en la matriz:
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) }Como otros han mencionado, hay formas de resolver esto en la creación de su matriz, pero dado que su LinkChecker parece estar donde los está limpiando específicamente, solo cambié ese método en aras de la claridad.
Es mejor evitar que corregir (el doble & ).
Elimina todo el bloque que hace push("") . Este impulso agrega una entrada a su matriz que realmente no desea tener en absoluto, así que simplemente no lo presione.