简体   繁体   English

如何防止多个“,”被附加在字符串中

[英]How to prevent multiple “, ” from being appended in the string

I am trying to basically check if the string ends with ", " then do not append another ", " . 我试图基本上检查字符串是否以“,”结尾,然后不附加另一个“,”。 If the string does not end with ", " then append ", ". 如果字符串不以“,”结尾,则追加“,”。 I just want one ", " in between two strings. 我只想在两个字符串之间插入一个“,”。 However as I hit the "compute" button of my script several times (which basically iterates the key values & appends the comma's between strings) , I get multiple ", " between two strings. 然而,当我多次点击我的脚本的“计算”按钮(基本上迭代键值并在字符串之间附加逗号)时,我在两个字符串之间得到多个“,”。 What I tried does not really work. 我尝试的并不是真的有效。

eg: 例如:

Expected is abc, apple, pear, strawberry even if I hit compute many times or one time 即使我多次或多次计算abc, apple, pear, strawberry预计是abc, apple, pear, strawberry

What I get after multiple clicks of compute button: 多次点击计算按钮后得到的结果:

abc, , , , apple, , , , pear, , , , strawberry

Here's what I tried: 这是我试过的:

//Here obj[key][i] is the string //这里obj [key] [i]是字符串

var lenson = obj[key][i].length;
if(1!=len-1){
if(obj[key][i].charAt(lenson-1) === " " && obj[key][i].charAt(lenson-2)=== ","){

}
else{
if(obj[key][i]!=""){
obj[key][i]+=", ";
}
}
li.appendChild(document.createTextNode( obj[key][i] ));

}

I am assuming you are getting your data from some sort of json object or similar. 我假设你从某种json对象或类似物体获取数据。 Since you are already looping over the keys, my advice would be to simple store them in an array. 由于您已经遍历了键,我的建议是将它们简单地存储在数组中。 Then when you want to output them to string you just use .join(",") 然后,当你想将它们输出到字符串时,你只需使用.join(",")

var list = yourarray.join(",");

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

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