JS split()函数忽略出现在引号内的分隔符

law*_*awx 1 javascript quotes split

基本上,就像你说的那样

var string = 'he said "Hello World"';
var splitted = string.split(" ");
Run Code Online (Sandbox Code Playgroud)

分裂的数组将是:

'he' 'said' '"Hello World"'
Run Code Online (Sandbox Code Playgroud)

基本上将引号标记部分视为单独的项目

那么我如何在javascript中执行此操作?如果扫描仪在一组引号内,我是否必须有一个遍历字符串检查的for循环?或者有更简单的方法吗?

4lb*_*toC 7

你可以使用正则表达式:

var splitted = string.match(/(".*?")|(\S+)/g);
Run Code Online (Sandbox Code Playgroud)

基本上它首先搜索引号(包括空格)之间的任何字符的字符串,然后搜索字符串中的所有剩余单词.

例如

var string = '"This is" not a string "without" "quotes in it"'; string.match(/(".*?")|(\S+)/g);

将其返回到控制台:

[""This is"", "not", "a", "string", ""without"", ""quotes in it""]
Run Code Online (Sandbox Code Playgroud)