【问题标题】:Split string on 2nd occurrence of characters JavaScript在第 2 次出现字符时拆分字符串 JavaScript
【发布时间】:2021-08-12 19:13:47
【问题描述】:

我想用逗号分割一个字符串,并且需要填充一个 JSON 数组。我有以下字符串数据

const test='00000001,name1,00000002,name2,00000003,name3,00000004,name4';

console.log(test.split('/[\n,|]/',2));

Output : ['00000001','name1','00000002','name2','00000003','name3','00000004','name4']

但我需要这样的输出

[{id:'00000001',name:'name1'},{id:'00000002',name:'name2'},{id:'00000003',name:'name3'},{id:'00000004',name:'name4'}]

【问题讨论】:

    标签: javascript arrays string split


    【解决方案1】:

    【讨论】:

    • 还有比map 更适合该任务的其他方法,map 是“语义上”而不是为了做需要做的事情。
    【解决方案2】:

    假设数组的长度是偶数,这个输出可以通过这样做来实现:

    const test='00000001,name1,00000002,name2,00000003,name3,00000004,name4';
    let words = test.split(",");
    let output = [];
    let obj = {};
    for (let i = 0; i < words.length; i++) {
      if (i % 2 == 0) {
      obj = {};
      obj["id"] = words[i];
      }
      
      else {
      obj["name"] = words[i];
      output.push(obj);
      }
    }
    console.log(output);

    【讨论】:

      【解决方案3】:

      您可以通过首先将字符串与/(\d)+,(\w)+/gi 匹配来轻松实现此结果。它会给你一个字符串数组。

      然后您可以使用map 来获得所需的结果。

      const test = "00000001,name1,00000002,name2,00000003,name3,00000004,name4";
      
      const regex = /(\d)+,(\w)+/gi;
      const result = test.match(regex).map((str) => {
        const [id, name] = str.split(",");
        return { id, name };
      });
      
      console.log(result);

      【讨论】:

        【解决方案4】:

        另一种方法是使用带有named capture groups 的模式。

        用于捕获id的数字,匹配逗号并捕获name的单词字符:

        (?<id>\d+),(?<name>\w+)
        

        const test = '00000001,name1,00000002,name2,00000003,name3,00000004,name4';
        const result = Array.from(
          test.matchAll(/(?<id>\d+),(?<name>\w+)/g),
          m => m.groups
        );
        console.log(result);

        如果要捕获 id 和 name 的所有字符(逗号或空格字符除外),您可以使用 negated character class [^,\s]+

        (?<id>[^,\s]+),(?<name>[^,\s]+)
        

        const test = '00000001,name1,00000002,name2,00000003,name3,00000004,name4';
        const result = Array.from(
          test.matchAll(/(?<id>[^,\s]+),(?<name>[^,\s]+)/g),
          m => m.groups
        );
        console.log(result);

        【讨论】:

          猜你喜欢
          • 2014-10-12
          • 2021-08-10
          • 1970-01-01
          • 2019-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-29
          • 1970-01-01
          相关资源
          最近更新 更多