const a = '/sport/football/1'; const b = '/football/1?a=1'¿Cómo puedo combinar estas 2 URL para obtener esta:
const c = '/sport/football/1?a=1';Nota: Básicamente, la primera URL puede tener un punto de partida diferente y la segunda puede tener varios parámetros de consulta. Pero tienen en común la parte media.
const a = "/sport/football/1"; const b = "/football/1?a=1"; const c = a + b.substring(b.indexOf("?")); console.log(c);Por la forma en que me parece su pregunta, desea poder fusionar dos URL de manera que la segunda se agregue a la primera si aún no está en la URL o se integre en la primera si hay un superposición.
Para eso, debe realizar algunas pruebas y modificar las cadenas para obtener el resultado que desea.
Aquí hay una posibilidad de resolver ese problema.
Problema conocido con esta solución: no manejará la repetición en una URL.
URL a = asd/dsa/asd/dsa/123?321=123 URL b = /dsa/asd/dsa/123?321=456 result = asd/dsa/asd/dsa/asd/dsa/123?321=456Si necesita cubrir ese caso, debe mejorar la sección de índice para encontrar la ocurrencia correcta.
// Editar: hubo un problema que permitía encontrar subcadenas de b en a, que se resolvió al convertir también la URL a en una matriz para la verificación
el error seria el siguiente:
URL a = asd/dsa/123 URL b = as/321 Result = as/321porque la URL b [0] (as) es una subcadena de asd en la URL a y, por lo tanto, sería encontrada por String.lastIndexOf
function calculateUrl(urla, urlb) { // we start by initialising the new url with URL a let ret = urla; // we split the URL a on / and cleaning it up to make sure we dont have an empty first value // we need this as a string check might cause a problem when part of aUrlb[0] is found in urla const aUrla = urla.split("/").filter(function(elm) { return typeof elm === "string" && elm.length > 0; }); // we split the URL b on / and cleaning it up to make sure we dont have an empty first value const aUrlb = urlb.split("/").filter(function(elm) { return typeof elm === "string" && elm.length > 0; }); // we generate a new string for URL b without a leeding / const appendix = aUrlb.join("/"); // we choose the first element of URL b to check if URL b is part of URL a or if it has to be appended const searchTerm = aUrlb[0]; // we perform the check const foundAt = aUrla.lastIndexOf(aUrlb[0]); if(foundAt !== -1) { // if we found that URL a and b have a overlap we only use the part of URL a that is unique ret = aUrla.slice(0, foundAt).join("/") + "/"; } else { // if we found that URL a and b do not have a overlap we need to make sure that URL a does not contain a ? ret = ret.split("?")[0] // we also need to make sure URL ends in / as we will append URL b to it if(ret.substring(ret.length - 1) !== "/") { ret = ret + "/"; } } // combine URL a and b return ret + appendix; } // ignore this, it's just so the button will work document.getElementById("calculate").addEventListener("click", function() { let p = document.createElement("p"); p.textContent = calculateUrl(document.getElementById("urla").value, document.getElementById("urlb").value); document.getElementById("output").appendChild(p); }); <label> URL A: <input id="urla"> </label> <br> <label> URL B: <input id="urlb"> </label> <br> <button id="calculate"> Calculate </button> <div id="output"></div>Traté de encontrar el último índice de todos los caracteres duplicados y luego los fusioné. avísame si algo no funciona correctamente.
const ur1 = '/sport/football/1'; const ur2 = '/football/1?a=1'; // get the last duplicate index let dupCount = 0, dupMark = 0; for(let a=0; a<ur1.length; a++){ for(let b=0; b<ur2.length; b++){ if( ur1[a+b] === ur2[b] ){ //console.log( ur1[a+b] +' : '+ ur2[b] ); dupCount += 1; if( ur2[b] !== '/' && dupCount > 0 ){ dupMark = b; } }else{ dupCount = 0; break; } } } console.log( 'last duplicate url index : '+ dupMark ); console.log( ur1+ur2.substr(dupMark) );