[英]Get portion of URL path and store value in string
所以我有下面的代码,我正在尝试获取 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);
我试图去掉 URL 中显示的 %20 符号和“,数据”部分,但我无法将整个 URL 缩小到字符串“Sarah's Day Salon”并将该值分配给商店名称变量。 现在,我能够将字符串缩小到以下,但是字符串开头存在巨大的间距问题,而且我也不确定这是否是捕捉“莎拉日沙龙”部分的最有效方式从网址。 我想知道是否有人对如何将 URL 缩小到仅商店名称有任何建议?
从上面的代码打印值:
storeName before: [ '', 'data', "Sarah's%20Day%20Salon" ]
storeName after: Sarah's Day Salon
您可以为此使用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.