简体   繁体   English

如何用多个分号分割字符串 javascript

[英]How to split string with multiple semi colons javascript

I have a string like below我有一个如下的字符串

var exampleString = "Name:Sivakumar; Tadisetti;Country:India"

I want to split above string with semi colon, so want the array like我想用分号分割上面的字符串,所以想要像这样的数组

var result = [ "Name:Sivakumar; Tadisetti", "Country:India" ]

But as the name contains another semi colon, I am getting array like但是由于名称包含另一个分号,所以我得到了类似的数组

var result = [ "Name:Sivakumar ", "Tadisetti", "Country:India" ]

Here Sivakumar; Tadisetti这里Sivakumar; Tadisetti Sivakumar; Tadisetti value of the key NameNameSivakumar; Tadisetti

I just wrote the code like exampleString.split(';') ... other than this not able to get an idea to proceed further to get my desired output.我刚刚编写了exampleString.split(';')之类的代码......除此之外,我无法进一步获得我想要的 output 的想法。 Any suggestions?有什么建议么?

Logic to split : I want to split the string as array with key:value pairs拆分逻辑:我想将字符串拆分为带有key:value对的数组

Since .split accepts regular expressions as well, you can use a one that matches semicolons that are only followed by alphanumeric characters that end in : ( in effect if they are followed by another key )由于.split也接受正则表达式,因此您可以使用与分号匹配的表达式,分号后仅跟以:结尾的字母数字字符(如果它们后跟另一个键则有效

/;(?=\w+:)/

 var exampleString = "Name:Sivakumar; Tadisetti;Country:India"; var result = exampleString.split(/;(?=\w+:)/); console.log(result)

here is an approach which we first split the input on ;这是一种我们首先将输入拆分的方法; and then concat the element without : with the previous one;然后将没有:的元素与前一个元素连接; since it shouldn't being spited.因为它不应该被怨恨。

 let exampleString = "Name:Sivakumar; Tadisetti;Country:India" let reverseSplited = exampleString.split(";").reverse(); let prevoiusString; let regex = /[^:]+:.*/; let result = reverseSplited.map( str => { if(regex.test(str)) { if(prevoiusString){ let returnValue = str + ";" + prevoiusString; prevoiusString = null; return returnValue } return str } prevoiusString = str; }).filter(e=>e); console.log(result);

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

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