3 回答
TA贡献1946条经验 获得超4个赞
我的做法:
const stringToProcess = '\'a="https://google.com/" b="Johnny Bravo" c="1" d="2" charset="z"\'';
const pair = /(\w+)="([^"]*)"/g;
const attributes = {};
while (true) {
const match = pair.exec(stringToProcess);
if (!match) break;
const [, key, value] = match;
attributes[key] = value;
}
console.log(attributes);
/*
{
"a": "https://google.com/",
"b": "Johnny Bravo",
"c": "1",
"d": "2",
"charset": "z"
}
*/
TA贡献1821条经验 获得超6个赞
如果你有一个固定的结构,那么如果你积极地匹配项目的结构,这种事情会效果更好。所以你可以做类似的事情...
'a="https://google.com/" b="Johnny Bravo" c="1" d="2" charset="z"'.match(/\w+=".*?"/gm)
TA贡献1891条经验 获得超3个赞
你正在寻找的是一个对象。您需要将初始字符串拆分为数组,然后将其从数组中转换为对象。我会这样做:
const str = 'a="https://google.com/" b="Johnny Bravo" c="1" d="2" charset="z"';
// Split using RegEx
const arr = str.match(/\w+=(?:"[^"]*"|\d*|true|false)/g);
// Create a new object.
const obj = {};
// Loop through the array.
arr.forEach(it => {
// Split on equals and get both the property and value.
it = it.split("=");
// Parse it because it may be a valid JSON, like a number or string for now.
// Also, I used JSON.parse() because it's safer than exec().
obj[it[0]] = JSON.parse(it[1]);
});
// Obj is done.
console.log(obj);
上面给了我:
{
"a": "https://google.com/",
"b": "Johnny Bravo",
"c": "1",
"d": "2",
"charset": "z"
}
您可以使用类似obj.charset
and 的东西,这会为您z
或obj.b
为您提供Johnny Bravo
。
添加回答
举报