简体   繁体   English

获取 URL 路径的一部分并将值存储在字符串中

[英]Get portion of URL path and store value in string

So I have code below, and I'm trying to get the store name part of the URL without the gibberish values in between.所以我有下面的代码,我正在尝试获取 URL 的商店名称部分,中间没有乱码值。

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

I attempt to get rid of the %20 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.我试图去掉 URL 中显示的 %20 符号和“,数据”部分,但我无法将整个 URL 缩小到字符串“Sarah's Day Salon”并将该值分配给商店名称变量。 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?我想知道是否有人对如何将 URL 缩小到仅商店名称有任何建议?

Printing values from code above:从上面的代码打印值:

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

you can use the decodeURI function for that, no need to replace the %20s with " ", just parse in the url as is and it will remove all special characters.您可以为此使用decodeURI函数,无需将 %20s 替换为“”,只需按原样解析 url,它将删除所有特殊字符。

 const url = "/data/Sarah's%20Day%20Salon"; const decodedString = decodeURI(url); const stringArray = decodedString.split('/'); const storeName = stringArray.at(-1); // I experimented with the above, the below line is what is ussually used to get the last line // const storeName = stringArray[stringArray.length - 1] console.log(storeName);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM