目前,我可以像这样分割一个字符串:
"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/