From the way your question looks to me you want to be able to merge two urls in a way the the second one will be appended to the first one if it is not yet in the url or be integrated into the first one if there is a overlap.
For that you need to do some testing and modifying of the strings to get to the result that you want.
Here is one possibility of solving that issue.
Known issue with this solution: it will not handle repitition in a 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=456
If you need to cover that case then you have to enhance the index section to find the correct occurence.
// Edit: There was an issue that allowed substrings of b to be found in a, that has been solved by also converting URL a to an array for the check
the error would be as follows:
URL a = asd/dsa/123
URL b = as/321
Result = as/321
because URL b [0] (as) is a substring of asd in URL a and would therefore be found by 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>