regex to find a string that comes after =

前端 未结 6 1224
萌比男神i
萌比男神i 2021-01-28 07:15

I´m really new to regex and I have been looking around to find an answer but either it dont work or I get some kind of error so I will try to ask the question and hopefulyl some

6条回答
  •  [愿得一人]
    2021-01-28 08:03

    .replace with a callback function is your tool of choice when parsing custom formats in javascript. Consider:

    parse = function(s) {
        var result = {};
        s.replace(/^(\w+)|\[(.+?)=(.+?)\]/g, function($0, $1, $2, $3) {
            result[$2 || "kind"] = $1 || $3;
        });
        return result;
    }
    

    Example:

    str = "car[brand=saab][wheels=4][price=1234][morestuff=foobar]"
    console.log(parse(str))
    // {"kind":"car","brand":"saab","wheels":"4","price":"1234","morestuff":"foobar"}
    

提交回复
热议问题