[英]How to split a string by “:” but keep the parts in quotes in JavaScript?
I'm trying to create a regex which splits a string by :
but don't split the quoted parts: 我想创造出由分割字符串中的正则表达式:
但不要分裂引用部分:
'a:b:c'.split(/*RegExNeeded*/) // => ['a','b','c']
'a:"1:2":d'.split(/*RegExNeeded*/) // => ['a','1:2', 'd']
I've tried ''.split(':')
but it is not working, because it'll split the 1:2
as well. 我试过了''.split(':')
但它不起作用,因为它也会将1:2
分割。
You could use look ahead to ensure that the number of double quotes that follows a colon is even (not odd): 您可以使用前瞻性来确保冒号后面的双引号数量是偶数(不是奇数):
var res = 'a:"1:2":d'.split(/:(?=[^"]*(?:"[^"]*"[^"]*)*$)/); console.log(res.join());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.