Home > Back-end >  Get portion of URL path and store value in string
Get portion of URL path and store value in string

Time:11-01

So I have code below, and I'm trying to get the store name part of the URL without the gibberish values in between.

    let storeName = request.url.split('/');
    console.log("storeName before: ", storeName);
    storeName = storeName.toString().replace(" ", " ");
    storeName = storeName.toString().replace(" ", " ");
    storeName = storeName.toString().replace(",data,", " ");
    console.log("storeName after: ", storeName);

I attempt to get rid of the symbols and ",data," part that show up in the URL, but I'm having trouble narrowing down that entire URL to just the string "Sarah's Day Salon" and assign that value to the storeName variable. Right now, I was able to narrow the string down to below, but there's a huge spacing issue at the start of the string, and I'm also not sure if this is the most efficient way to capture the "Sarah's Day Salon" part from the URL. I was wondering if anyone has any suggestions as to how I could narrow the URL down to just the store name only?

Printing values from code above:

    storeName before:  [ '', 'data', "Sarah's Day Salon" ]
    storeName after:   Sarah's Day Salon

CodePudding user response:

you can use the decodeURI function for that, no need to replace the s with " ", just parse in the url as is and it will remove all special characters.

const url = "/data/Sarah's Day Salon";
const decodedString = decodeURI(url);
const stringArray = decodedString.split('/');
const storeName = stringArray[stringArray.length - 1]
console.log(storeName);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related