我有一个如下所示的字符串:
var String = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma,xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"
其中xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
代表字母数字生成的Id,冒号之后是与该Id相关的字符串。字符串可以是逗号或不带逗号的字符串。我想要的是我想要分割字符串等我得到一个带ID的数组:它对应的字符串,如下所示。
["xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string,with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string without comma",
"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:some string , with comma","xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx:String,with comma"]
我如何实现
我使用了javascript split函数,其中我用逗号分隔字符串,后跟36个字符(用于ID)和冒号。
String.split(/,(?=.{36}:)/);
PS:我道歉,因为我以前无法以正确的方式提问。希望这次人们能理解。
答案 0 :(得分:4)
您可以使用逗号String#split
并预览数字和冒号。
var x = "123456:a,b,c,435213:r,567876:e,363464:t,y,u";
array = x.split(/,(?=\d+:)/);
console.log(array);
对于字母数字值
var x = "1A3456:a,b,c,43Y213:r,567W76:e,363x64:t,y,u";
array = x.split(/,(?=[a-z0-9]+:)/i);
console.log(array);
答案 1 :(得分:0)
您可以使用方法.split()。我使用" $"作为分裂符号代替","因为我以为你想保留它们。
var values = "123456:a,b,c$435213:r$567876:e$363464:t,y,u".split("$");
var x = values[0];
console.log(values)