what is the best way to extract variables with '=' from a string in javascript

后端 未结 4 714
再見小時候
再見小時候 2021-01-29 07:40

I want to extract the variables names from a string like this: \"foo=valor bar=second\", and so on.

To return:

{ 
   foo: \"valor\", 
   ba         


        
4条回答
  •  日久生厌
    2021-01-29 08:30

    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);

提交回复
热议问题