除非使用双引号引起来,否则将字符串拆分为带有空格的单词

除非使用双引号引起来,否则将字符串拆分为带有空格的单词

问题描述:

我想分割此字符串:

从任何站点"获取内容"

get "something" from "any site"

要数组. 我已经做到了:

to array. I've done that:

var array = $(this).val().replace(/\s+/g, ' ').split(" ");

但是我不想在引号(")中拆分单词.

But I don't want to split words in quotation marks ("").

是否可以通过简单的方式完成?

whether it can be done in a simple way?

一种解决方案:

var str = 'get "something" from "any site"';
var tokens = [].concat.apply([], str.split('"').map(function(v,i){
   return i%2 ? v : v.split(' ')
})).filter(Boolean);

结果:

["get", "something", "from", "any site"]

有可能做得更简单.这里的想法是使用"进行拆分,然后将第一次拆分的奇数结果按空格进行拆分.

It's probably possible to do simpler. The idea here is to split using " and then split by the space the odd results of the first splitting.

如果要保留报价,可以使用

If you want to keep the quotes, you may use

var tokens = [].concat.apply([], str.split('"').map(function(v,i){
     return i%2 ? '"'+v+'"' : v.split(' ')
})).filter(Boolean);

结果:

['get', '"something"', 'from', '"any site"']