[英]Javascript - Extract part of a string lying between two special characters
I have strings like these-我有这样的字符串-
countries=a,b&states=c,d&districts=e,f,g,h
countries=a,b
I want to extract the part of the string which is lying between the characters =
and &
and return the result as an array.我想提取位于字符
=
和&
之间的字符串部分,并将结果作为数组返回。 So, in the first case, the result should be ['a','b', 'c','d','e','f','g','h']
.所以,在第一种情况下,结果应该是
['a','b', 'c','d','e','f','g','h']
。 In the second case, it should be ['a','b']
.在第二种情况下,它应该是
['a','b']
。 I achieved the result by doing like this-我通过这样做达到了结果-
const extract = string.split('&');
const splitArray = extract.map(x => x.split('=')[1]);
const resultString = splitArray.join(',');
const result = resultString.split(',');
Can I do it more concisely and in a better way?我可以更简洁、更好地做到这一点吗?
One example using URLSearchParams一个使用URLSearchParams的例子
let query = 'countries=a,b&states=c,d&districts=e,f,g,h';
let values = [];
(new URLSearchParams(query)).forEach(function(v) {
v.split(',').forEach(function(v){
values.push(v);
});
});
console.log(values); // ["a", "b", "c", "d", "e", "f", "g", "h"]
... but if by "concise" you mean "one-liner".. well here's my take: ...但是如果“简洁”是指“单线”..这是我的看法:
let query = 'countries=a,b&states=c,d&districts=e,f,g,h';
query = query.replace(/(^|&).*?=/g,',').split(',').filter(Boolean);
console.log(query); // ["a", "b", "c", "d", "e", "f", "g", "h"]
const input = [ 'countries=a,b&states=c,d&districts=e,f,g,h', 'countries=a,b' ]; input.forEach((line) => { let result = [].concat.apply([], line.split(/&/).map((keyValue) => { return keyValue.replace(/^[^=]*=/, '').split(/,/) })); console.log(line + ' ==> ' + JSON.stringify(result)); });
Output: Output:
countries=a,b&states=c,d&districts=e,f,g,h ==> ["a","b","c","d","e","f","g","h"]
countries=a,b ==> ["a","b"]
Explanation:解释:
&
to get key/value pairs&
拆分以获取键/值对'
'
[].concat.apply([], arr)
[].concat.apply([], arr)
展平生成的 arrays 数组Alternatively you could initialize an empty array []
, and as a last step of for each key/value, do a forEach on each item, and push it to the array.或者,您可以初始化一个空数组
[]
,并作为每个键/值的最后一步,对每个项目执行 forEach ,并将其推送到数组中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.