javascript 如何从javascript中的拆分字符串中删除逗号(,)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9111285/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to remove comma(,) from splitted string in javascript?
提问by Arpi Patel
I have used split function to split the string in javascript. which is as,
我使用 split 函数在 javascript 中拆分字符串。即,
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 jabclab
By default the .toString()
of an Array
will use comma as its delimiter, just use the following:
默认情况下.toString()
,Array
将使用逗号作为分隔符,只需使用以下内容:
var str = test.join("");
Whatever you pass as the argument to join
will be used as the delimiter.
无论您作为参数传递给什么,join
都将用作分隔符。
回答by Eden
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:
rwz 在拆分字符串之前修剪字符串的答案绝对更简单。对于这个例子,可以像这样调整:
event_display1 = event_display1.replace(/#,#/g, "##")
var test = event_display1.split("#");
回答by Pavel Pravosud
If your output string consists of multiple strings (using \n character), you can remove unwanted commas with this code:
myString.replace(/\,(?:\n|$)/g, "\n")
如果您的输出字符串包含多个字符串(使用 \n 字符),您可以使用以下代码删除不需要的逗号:
myString.replace(/\,(?:\n|$)/g, "\n")