【问题标题】:How split string with nested strings如何用嵌套字符串拆分字符串
【发布时间】:2019-12-19 12:44:28
【问题描述】:

我有一个这样的字符串

const str = "'a' 'b' 'c'"

我想拆分它并得到字符串的结果数组

const arr = str.split(" ")

但在输出中我得到:

["'a'", "'b'", "'c'"]

如何在没有嵌套字符串的情况下进入输出数组?

想要的结果

["a", "b", "c"]

【问题讨论】:

  • 这些字符串中的一个是否有可能转义 ' 字符?例如["'doesn\'t' 'abc' 'mustn\'t'"]
  • Array.from(text.matchAll(/'([^']+)'/g), m => m[1])
  • Array.from(text.matchAll(/'([^'\\]*(?:\\.[^'\\]*)*)'/gs), m => m[1])

标签: javascript arrays regex split


【解决方案1】:

您可以通过传递 regex 表达式来使用 replace 方法,并通过将 箭头函数 传递为 argument 结合 map 方法。

const str = "'a' 'b' 'c'";
console.log(str.split(' ').map(el => el.replace(/'/g, "")));

【讨论】:

    【解决方案2】:

    首先使用.replace()从上面的字符串中删除',然后将其拆分:

    const str = "'a' 'b' 'c'";
    
    const output = str.replace(/'/g, '').split(' ');
    
    console.log(output);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-26
      • 2014-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多