【发布时间】:2018-08-06 05:54:18
【问题描述】:
我有以下字符串:
person:juan&age:24&knowledge:html
问题是有时字符串是:
knowledge:html&person:juan&age:24
它可以改变键和值的位置。
在这种情况下,我会这样写:
const keys = ["person", "age", "knowledge"];
const keyAndValues = "person:juan&age:24&knowledge:html";
const result = [];
keys.forEach(key => {
const indexKeyValues = keyAndValues.indexOf(key);
if (indexKeyValues !== -1) {
const lastCharIndex = keyAndValues.substring(indexKeyValues).indexOf("&");
return keyAndValues.substring(indexKeyValues + key.length, lastCharIndex === -1 ? keyAndValues.substring(indexKeyValues).length - 1 || lastCharIndex);
}
});
但我不喜欢它,如果我能做这样的事情会很棒:
const resultsExpected = /regexGroupedRegardlessOfPosition/g.match("person:juan&age:24&knowledge:html");
console.log(resultsExpected); // { person: "juan", age: 24, knowledge: "html" }
【问题讨论】:
-
我不认为正则表达式在这种情况下是最好的解决方案。老实说,我什至不认为它适用于这个问题的任何解决方案。
-
为什么可能有办法在:和链的开头之间抓取东西,看它是否属于某个键,然后抓取值
-
我认为如果它有效,你应该使用你所拥有的。它简单易读,老实说,正则表达式很少。
-
看起来你最好在
&上拆分字符串,然后在:上拆分每个结果 -
听起来很合理@MattBurland,这也会使其更具可读性
标签: javascript arrays regex string object