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?
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?
Share Improve this question asked Feb 2, 2012 at 11:09 Arpi PatelArpi Patel 7854 gold badges10 silver badges23 bronze badges 1- showing the original input and code would be even better – Alnitak Commented Feb 2, 2012 at 11:14
3 Answers
Reset to default 11By 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("#");
If your output string consists of multiple strings (using \n character), you can remove unwanted commas with this code:
myString.replace(/\,(?:\n|$)/g, "\n")