简体   繁体   English

如何在 url 中用分号替换逗号作为分隔符

[英]How to replace comma with semicolon as delimiter in url

I am attempting to add a combination of products and quantities to the end of a url string.我正在尝试将产品和数量的组合添加到 url 字符串的末尾。 Each combination of product/quantity is separated by a semi-colon rather than a comma.产品/数量的每个组合都用分号而不是逗号分隔。

This is what I did: https://test.com?products=81:1,77:1,107:1这就是我所做的: https://test.com?products=81:1,77:1,107:1

This is what I want: https://test.com?products=81:1;77:1;107:1这就是我想要的: https://test.com?products=81:1;77:1;107:1

The below code is how I am building the prods array and the prods returned is what is added to the end of the url.下面的代码是我如何构建 prods 数组,返回的 prods 是添加到 url 末尾的内容。

json.forEach(function (obj) { 
    prods.push(obj.product_id + ':' + obj.quantity); 
});

return prods;
return prods;

returns the toString of an array with comma separators.返回带有逗号分隔符的数组的 toString。

Just change to只需更改为

return prods.join(':');

Actually just do其实只是做

return json.map(obj => `${obj.product_id}:${obj.quantity}`).join(';');

I have below a snippet of code which creates a 'template URL' based on your criteria.我在下面有一段代码,它根据您的标准创建一个“模板 URL”。 The semicolon comes from using join which converts the array of product:quantity into a string joined by semicolons.分号来自使用join ,它将 product:quantity 数组转换为由分号连接的字符串。

Note that I decided you could use a more general purpose approach because you do not provide us with the data structure of your JSON, so the snippet I created is agnostic to that and instead focuses on you leveraging the result to your liking.请注意,我决定您可以使用更通用的方法,因为您没有向我们提供 JSON 的数据结构,因此我创建的代码段与此无关,而是专注于您根据自己的喜好利用结果。

 var makeProductUrl = (array) => { var products, templateUrl = 'http://test.com?products='; products = array.map((elem) => { return `${elem.product_id}:${elem.quantity}`; }).join(';') return `${templateUrl}${products}`; }; var someArray = [ { product_id: 'A', quantity: 1 }, { product_id: 'A', quantity: 123 }, { product_id: 'A', quantity: 88 }, { product_id: 'D', quantity: 12 }, ], url = makeProductUrl(someArray); alert(url);

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

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