【问题标题】:How can I split a string input in Javascript by each spacebar, but not elements inside double "quotes", single 'quotes' or backticks [duplicate]如何按每个空格键拆分 Javascript 中的字符串输入,但不能拆分双“引号”、单“引号”或反引号内的元素 [重复]
【发布时间】:2021-12-20 11:17:16
【问题描述】:

我正在尝试通过执行以下操作从字符串中获取参数数组

const str = `argument "second argument" 'third argument' \`fourth argument\``;

str.split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g);

预期输出:

['argument', '"second argument"', "'third argument'", '`fourth argument`']

但是结果出来了:

['argument', '`', '"second argument"', '`', "'third argument'", '`', '`fourth argument`']

我怎样才能取回一个只有 4 个元素的数组?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    得到一个数组后就可以使用filter过滤掉不需要的字符串

    const str = `argument "second argument" 'third argument' \`fourth argument\``;
    
    const result = str
      .split(/\s(?=(?:[^'"`]*(['"`])[^'"`]*\1)*[^'"`]*$)/g)
      .filter((s) => /[a-z]/.test(s));
    
    console.log(result);

    您也可以使用字符串操作实现相同的结果

    const str = `argument "second argument" 'third argument' \`fourth argument\``;
    
    const replacerFn = (match) => match.split(" ").join("_");
    const result = str
      .replace(/".*?"|'.*?'|`.*?`/g, replacerFn)
      .split(" ")
      .map((s) => s.split("_").join(" "));
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      我建议你在拆分为数组之前标准化你的字符串

      将所有 ` 替换为 " 等等

      【讨论】:

        猜你喜欢
        • 2017-02-19
        • 2020-08-03
        • 2020-11-06
        • 1970-01-01
        • 2019-11-09
        • 2017-01-05
        • 2011-12-25
        相关资源
        最近更新 更多