简体   繁体   中英

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

I have used split function to split the string in 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:

var str = test.join("");

Whatever you pass as the argument to join will be used as the delimiter.

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. 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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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