除非使用双引号引起来,否则将字符串拆分为带有空格的单词 [英] Split string into words with whitespace unless in between a pair of double quotation marks

查看:61
本文介绍了除非使用双引号引起来,否则将字符串拆分为带有空格的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分割此字符串:

从任何站点"获取内容"

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"']

这篇关于除非使用双引号引起来,否则将字符串拆分为带有空格的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆