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

后端 未结 4 712
再見小時候
再見小時候 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:31

    Not necessarily the quickest answer (in terms of speed of submission), but less regular expressions to maintain and less variables to store.

    function toJSON(str) {
      const regex = /(\w+)\=(\w+)\s*/g;
      let result = {};
      let match;
    
      while (match = regex.exec(str)) {
        result[match[1]] = match[2];
      }
    
      return result;
    }
    
    console.log(toJSON("foo=valor bar=second"));
    

提交回复
热议问题