简体   繁体   English

在两个定界符上分割字符串?

[英]Split string on two delimiters?

I want to split a string based on the delimiters " " and "," (including quotation marks). 我想基于定界符" ""," (包括引号)拆分字符串。 How would I be able to do this? 我将如何做到这一点? I tried doing this: 我尝试这样做:

 var str = '"String","String2" "String3"'; str = str.split('" "', '","'); console.log(str); 

But it didn't work. 但这没有用。 I was expecting this console output: 我期待这个控制台输出:

["String", "String2", "String3"]

But I got: 但是我得到了:

[]

How do I split a string based on two delimiters? 如何基于两个定界符分割字符串? Is it possible? 可能吗?

 let str = '"String","String2" "String3"'; str = str.split(/ |,/); console.log(str); let str2 = '"String","String2" "String3"'; str2 = str2.split(/" "|","|"|\\n/).filter(Boolean); console.log(str2); let str3 = '"String","String2" "String3"'; str3 = str3.match(/[\\w\\d]+/g); console.log(str3); 

您可以使用正则表达式: str = str.split(/,| /)

 console.log("a,bc".split(/,| /)); 

try below solution 尝试以下解决方案

 var str = '"String","String2" "String3"'; str = str.match(/\\w+|"[^"]+"/g) str = str.map(function(x){return x.replace(/"/g, '');}); console.log('Final str : ', str); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM