I want to extract the variables names from a string like this: \"foo=valor bar=second\"
, and so on.
To return:
{
foo: \"valor\",
ba
You can use Regex Look Aheads to check for a variable name that is preceded by an =
symbol
var str = "foo=valor bar=second";
var varRegex = /\w+(?=(\s)*(\=))/g;
var valueRegex = /(?<=(\=)[\s'"]*)\w+/g;
var varArr = str.match(varRegex);
var valueArr = str.match(valueRegex);
console.log(valueArr);
let obj = {};
for(let i in varArr) {
obj[varArr[i]] = valueArr[i];
}
console.log(obj);