从逗号分隔的字符串中删除一个数字,同时正确删除逗号 [英] Remove a number from a comma separated string while properly removing commas

查看:294
本文介绍了从逗号分隔的字符串中删除一个数字,同时正确删除逗号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例:给出一个字符串..."1,2,3,4"

FOR EXAMPLE: Given a string... "1,2,3,4"

我需要能够删除给定的数字和逗号前后的逗号,具体取决于匹配项是否在字符串的末尾.

I need to be able to remove a given number and the comma after/before depending on if the match is at the end of the string or not.

删除(2)="1,3,4"

remove(2) = "1,3,4"

删除(4)="1,2,3"

remove(4) = "1,2,3"

另外,我正在使用javascript.

Also, I'm using javascript.

推荐答案

正如jtdubs所示,一种简单的方法是使用split函数获取不带逗号的元素数组,从数组中删除所需的元素,然后然后使用连接函数重建字符串.

As jtdubs shows, an easy way is is to use a split function to obtain an array of elements without the commas, remove the required element from the array, and then rebuild the string with a join function.

对于javascript来说,这样的方法可能有效:

For javascript something like this might work:

function remove(array,to_remove)
{
  var elements=array.split(",");
  var remove_index=elements.indexOf(to_remove);
  elements.splice(remove_index,1);
  var result=elements.join(",");
  return result;
}

var string="1,2,3,4,5";
var newstring = remove(string,"4"); // newstring will contain "1,2,3,5"
document.write(newstring+"<br>");
newstring = remove(string,"5"); 
document.write(newstring+"<br>"); // will contain "1,2,3,4"

如果重复,您还需要考虑所需的行为,例如,字符串为"1、2、2、4",我说"remove(2)",它应该同时删除两个实例还是仅删除第一个实例?此功能将仅删除第一个实例.

You also need to consider the behavior you want if you have repeats, say the string is "1,2,2,4" and I say "remove(2)" should it remove both instances or just the first? this function will remove only the first instance.

这篇关于从逗号分隔的字符串中删除一个数字,同时正确删除逗号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆