你正在寻找的是一个对象。您需要将初始字符串拆分为数组,然后将其从数组中转换为对象。我会这样做:
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.charsetand 的东西,这会为您z或obj.b为您提供Johnny Bravo。对于正则表达式,这里是演示。
DIEA
相关分类