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

后端 未结 4 711
再見小時候
再見小時候 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:21
    var str = "foo=valor,bar=second";
    
    var obj = {};
    
    str.split(",").forEach(
         function(item){
         if(item){ 
            var vars = item.split("="); 
            obj[vars[0]] = vars[1] 
          }
     });
     console.log(obj)
    
    0 讨论(0)
  • 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);

    0 讨论(0)
  • 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"));
    
    0 讨论(0)
  • 2021-01-29 08:43

    Different approach from the previous answer: You can split the string on spaces and then map the result array, splitting on the equal sign to create your object (left side is property, right side is value)

    If you need it your specific format you can reduce it to convert the array into one big object with all the values

    let a = "foo=valor bar=second"
    
    console.log(a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);}))
    
    
    let b = a.split(' ').map((i,v) => { return JSON.parse(`{"${i.split('=')[0]}": "${i.split('=')[1]}"}`);})
    
    
    console.log(b.reduce(function(acc, x) {
        for (var key in x) acc[key] = x[key];
        return acc;
       }));

    0 讨论(0)
提交回复
热议问题