// function to find the nth instance of character in string
function nthIndex(str, pat, n) {
var L = str.length,
i = -1;
while (n-- && i++ < L) {
i = str.indexOf(pat, i);
if (i < 0) break;
}
return i;
}
// this function takes a string and split string list as parameters and slices off entirely after that character is found
function splitSliceFunc(splitStr, splitStrList) {
for (i = 0; i < splitStrList.length; i++) {
splitStr = splitStr.split(splitStrList[i])[0];
}
return splitStr;
}
try {
const amzUrl = 'https://www.amazon.com/Encyclopedia-Country-Living-50th-Anniversary/dp/1632172895/ref=sr_1_1?keywords=survival+encyclopedia&pd_rd_r=8e62738c-ae2b-46c0-b477-db5cf23a6b0a&pd_rd_w=0Eazc&pd_rd_wg=E51TF&pf_rd_p=54cea6b7-0efb-45a3-b68b-8c1ccfbfa553&pf_rd_r=EE9X3J3QBPCDQAVQJ9FQ&qid=1651929404&sr=8-1';
const sliceUptoAsinList = ["/dp/", "/gp/product/"]; // list for slice occurrences before asin
const sliceAfterAsinList = ["/", "?"]; // list for slice occurrences after the asin
let sliceUptoAsin; // variable to store index of slice occurrence before asin
let shortenedUrl;
// if else statements for all the possible slice occurrences before asin
if (amzUrl.includes(sliceUptoAsinList[0])) {
sliceUptoAsin = nthIndex(amzUrl, "/dp/", 1);
shortenedUrl = amzUrl.slice(sliceUptoAsin + 4); // + 4 to remove /dp/ also
console.log(sliceUptoAsin, shortenedUrl);
} else if (amzUrl.includes(sliceUptoAsinList[1])) {
sliceUptoAsin = nthIndex(amzUrl, "/gp/product/", 1);
shortenedUrl = amzUrl.slice(sliceUptoAsin + 12); // + 12 to remove /gp/product/ also
console.log(sliceUptoAsin, shortenedUrl);
} else {
throw "url format not supported";
}
// removes everything after the asin following 'sliceAfterAsinList'
shortenedUrl = splitSliceFunc(shortenedUrl, sliceAfterAsinList);
console.log(shortenedUrl);
} catch (error) {
console.log(error)
}
I opted for a non regex approach because they become harder to maintain. IF you are treating the urls as simple strings, split and slice can also do the job.
The above code assumes that the ASIN is followed by "/dp/" or "/gp/product/" (*but is not limited to these occurrences only because 'sliceUptoAsinList' array can have as many as slice occurrences before ASIN as many you want, followed by an added else-if condition).
The code will work irrespective of whether there are 10 or more characters in ASIN because it will only look for the first occurrence of any character found in the 'sliceAfterAsinList' array in the url and will remove everything next to that character (including the character also).