【问题标题】:Split string into array by space, but keeping phrases between quotes (including spaces) as a whole element按空格将字符串拆分为数组,但将引号(包括空格)之间的短语作为一个整体元素
【发布时间】:2025-12-24 23:20:16
【问题描述】:

例子:

test "testing 123! :)" // -> ['test', 'testing 123! :)']

test "\"testing these are some nice quotes!\"" // -> ['test', '"testing these are some nice quotes!\"']

有没有办法用 JavaScript 中的正则表达式来做到这一点?也许它也可以与 --flag=value 一起使用!

【问题讨论】:

标签: javascript arrays regex


【解决方案1】:

试试看。

const exemple = `testA testB "testC testD  " testE `
const textArray = exemple
  .split(new RegExp(`("[\\s\\S]*")`, 'g'))
  .flatMap(text => text.match(`"`) ? text : text.split(`\\s+`))

Exemple image

【讨论】:

    最近更新 更多