代码之家  ›  专栏  ›  技术社区  ›  prgrmr

解析模板化字符串

  •  1
  • prgrmr  · 技术社区  · 6 年前

    const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'
    

    我想解析这个字符串来生成一个类似于

    [{id: 'a', map: 'b'},
    {id: 'foo', map: 'bar'},
    {id: 'alpha', map: 'beta'}]
    

    2 回复  |  直到 6 年前
        1
  •  3
  •   ggorlen Hoàng Huy Khánh    6 年前

    下面是一个适用于您当前案例的正则表达式:

    const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");';
    
    const res = str.split(";").map(e => {
      const k = e.match(/map\("(.+?)"\)to\("(.+?)"\)/);
      return k && k.length === 3 ? {id: k[1], map: k[2]} : null;
    }).filter(e => e);
    
    console.log(res);

    map 这些对根据解析 map("")to("") 格式。最后, null 过滤掉所有的。

        2
  •  0
  •   AnC    6 年前

    我很确定有一个很好的正则表达式解决方案,它更短更快,但由于我不擅长正则表达式,我会这样解决这些问题:

    const str = 'map("a")to("b");map("foo")to("bar");map("alpha")to("beta");'
    
    const result = str.split(';').map(e => {
    
      const parts = e.substring(3).split('to').map(item => item.replace(/\W/g, ''));
    
      return {
        id: parts[0],
        map: parts[1]
      };
    })
    console.log(result);