While it may be unlikely to occur, the URL could contain a hostname with a top-level domain supplier. Currently .supplies is registered to Donuts Inc and someday URLs could have a TLD with supplier, which would lead the current code to not correctly find the target text.
const supplyUrl = "https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars"
if(supplyUrl.includes('?')) {
const url = supplyUrl.split('?')
if(url.length > 0) {
const tariff = url[0].split('supplier/')
console.log('tariff:', tariff[1])
}
}
A more robust solution would use the URL API with the pathname property. For example, if it was known that the last part of the pathname was the tariff string then the array method .pop() could be used:
const supplyUrl = "https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars"
console.log('tariff: ', new URL(supplyUrl).pathname.split(/\//).pop());
Otherwise if there is a need to find strings anywhere in the path that start with tariff then a pattern match could be used for that - for example:
const supplyUrl = "https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars"
function findTariff(url) {
const pathParts = new URL(url).pathname.split(/\//);
for (const part of pathParts) {
if (part.match(/^tariff/)) {
return part;
}
}
return -1; // or something to signify not found
}
console.log('tariff: ', findTariff(supplyUrl));
Or one could take a functional approach, which can be more concise:
const supplyUrl = "https://my.supplier/supplier/tariffSelectionG_E5449168?t=randomChars"
function findTariff(url) {
const pathParts = new URL(url).pathname.split(/\//);
return pathParts.find(part => part.match(/^tariff/));
}
console.log('tariff: ', findTariff(supplyUrl));