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

后端 未结 4 713
再見小時候
再見小時候 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: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;
       }));

提交回复
热议问题