简体   繁体   English

如何从javascript中的拆分字符串中删除逗号(,)?

[英]how to remove comma(,) from splitted string in javascript?

I have used split function to split the string in javascript. 我已经使用split函数在javascript中拆分字符串。 which is as, 就像

   test= event_display1.split("#");

This works perfectly and giving me output as, 这可以完美地工作,并且给我输出为

   Event Name : test1
   Location : test, test, test
   ,
   Event Name : test2
   Location : test, test, test
   ,

But i want my output as 但是我希望我的输出为

   Event Name : test1
   Location : test, test, test

   Event Name : test2
   Location : test, test, test

When i split the value it set comma after the character which i have used as split character. 当我分割数值时,它在我用作分割字符的字符后设置逗号。

How can i remove this comma from my output value? 如何从输出值中删除此逗号?

By default the .toString() of an Array will use comma as its delimiter, just use the following: 默认情况下, Array.toString()将使用逗号作为其定界符,只需使用以下命令:

var str = test.join("");

Whatever you pass as the argument to join will be used as the delimiter. 无论你传递作为参数join将用作分隔符。

As mentioned in the comments it would be really useful to see the input. 如评论中所述,查看输入将非常有用。 I'll assume a structure based on your output. 我将根据您的输出假设一个结构。 You could remove the commas from the array after you have split it, like this: 拆分后,可以从数组中删除逗号,如下所示:

var event_display1 = "Event Name : test1#Location : test, test, test#,#Event Name : test2#Location : test, test, test#,#";
var test = event_display1.split("#");

for (var i = event_display1.length - 1; i >= 0; i--) {
   if (test[i] == ",") {
          //Use test.slice(i, 1); if you want to get rid of the item altogether
          test[i] = "";
   }
}

rwz's answer of trimming the string before splitting it is definitely simpler. rwz的答案是在拆分之前先修剪字符串,这显然更简单。 That could be tweaked for this example like this: 可以针对以下示例进行调整:

event_display1 = event_display1.replace(/#,#/g, "##")
var test = event_display1.split("#");

如果输出字符串由多个字符串组成(使用\\ n字符),则可以使用以下代码删除不需要的逗号: myString.replace(/\\,(?:\\n|$)/g, "\\n")

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

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