javascript - 按空格拆分字符串,忽略嵌套字符串中的空格

标签 javascript

目前,我可以像这样分割一个字符串:

"1 2 3".split(' ') // [ "1", "2", "3" ]
"1 2 3 'word'".split(' ') // [ "1", "2", "3", "'word'" ]

有没有办法避免在嵌套字符串中的空格处拆分?

例如:

"1 2 3 'word one'".split(' ') // want output of [ "1", "2", "3", "'word one'" ]
"1 2 3 \"word one\"".split(' ') // want output of [ "1", "2", "3", "\"word one\"" ]

我想要输出 [ "1", "2", "3", "'word one'"] 而不是 [ "1", "2", "3 ", "'word", "one'"](即如果空格在字符串中,我想忽略它们)。

最佳答案

一种方法是使用 match使用正则表达式来解释引号内的空格:

var s = "1 2 3 \"word one\" one \"two\" 'hello world'";

console.log(s.match(/'[^']+'|"[^"]+"|\w+/g));

编辑:参见Certain Performance's answer以获得更好的正则表达式。

关于javascript - 按空格拆分字符串,忽略嵌套字符串中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53530154/

相关文章:

javascript - 在代理后面使用 node-gcm

javascript - 如何在浏览器窗口调整大小时自动调整 iframe 内容大小?

javascript - 如何隐藏/显示 Highcharts 基本柱形图中的列?

javascript - Vue-加载响应时显示 div

javascript - WebStorm 中的代码补全就像 ReSharper for Visual Studio 一样

JavaScript--将两个数组对象合并为一个 arr 对象,然后循环遍历每个索引/对象

javascript - 通过 jquery 检查具有相同类的下拉框中输入的重复值

javascript - 我们在哪些浏览器上使用 Paul Irish 的 requestAnimationFrame shim?

javascript - SWFUpload 未初始化

javascript - 如何在不滚动内容的情况下删除滚动条?