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
。
添加回答
舉報