Warm tip: This article is reproduced from serverfault.com, please click

regex-从逗号分隔的字符串中删除一个数字,同时正确删除逗号

(regex - Remove a number from a comma separated string while properly removing commas)

发布于 2010-11-24 22:59:13

例如:给定字符串...“ 1,2,3,4”

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

remove(2)=“ 1,3,4”

remove(4)=“ 1,2,3”

另外,我正在使用javascript。

Questioner
Derek Adair
Viewed
11
93 2019-02-13 13:17:58

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

对于javascript,可能会这样:

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)”,它应该删除两个实例还是只删除第一个实例?此函数将仅删除第一个实例。