[英]How do I split a string with multiple separators acting only as one in javascript?
我想使用“空格和逗号”(“,”)作为分隔符将字符串拆分为数组。 通过研究一些类似的问题,我弄清楚了如何使它们作为一个分隔符起作用。 但是我希望他们只能作为一个人工作。 因此,我不希望将数组仅用逗号或仅空格分隔。 因此,我希望字符串"txt1, txt2,txt3 txt4, txt 5"
成为数组txt1, "txt2,txt3 txt4", "txt 5"
这是我当前的代码,不能执行此操作:
var array = string.split(/(?:,| )+/)
这是jsFiddle的链接: http : //jsfiddle.net/MSQxk/
只要做: var array = string.split(", ");
你可以用这个
var array = string.split(/,\s*/);
//=> ["txt1", "txt2", "txt3", "txt4", "t x t 5"]
这将补偿像
// comma separated
foo,bar
// comma and optional space
foo,bar, hello
如果要补偿逗号两侧的可选空格,可以使用以下方法:
// "foo,bar, hello , world".split(/\s*,\s*);
// => ['foo', 'bar', 'hello', 'world']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.