我有这个字符串1,2,3,4,5
假设我去掉1,然后它变成,2,3,4,5或1,2,4,5
如何从列表中删除"1“或任何数字,并替换那些多余的逗号,同时还要记住最后一个数字"5”没有逗号。
我可以使用字符串替换javascript函数,我更关心的是最后一个数字
例如,如果我移去5,它应该显示为1,2,3,4
发布于 2010-11-12 02:14:48
theString.replace(/«the number»,?|,«the number»$/, '')>>> "1,2,3,4,5".replace(/1,?|,1$/, '')
"2,3,4,5"
>>> "1,2,3,4,5".replace(/2,?|,2$/, '')
"1,3,4,5"
>>> "1,2,3,4,5".replace(/5,?|,5$/, '')
"1,2,3,4"或者将字符串视为数组,使用
theString.split(/,/).filter(function(x){return x!="«the number»";}).join(",")>>> "1,2,3,4,5".split(/,/).filter(function(x){return x!="1";}).join(",")
"2,3,4,5"
>>> "1,2,3,4,5".split(/,/).filter(function(x){return x!="2";}).join(",")
"1,3,4,5"
>>> "1,2,3,4,5".split(/,/).filter(function(x){return x!="5";}).join(",")
"1,2,3,4"发布于 2010-11-12 02:15:09
不要使用正则表达式。使用数组。您可以将字符串split()到逗号上的数组中,然后根据需要删除这些元素。然后,您可以使用join()将它们重新组合为一个字符串。
发布于 2010-11-12 02:36:53
function removeValue(value, commaDelimitedString)
{
var items = commaDelimitedString.split(/,/);
var idx = items.indexOf(value);
if(idx!=-1) { items.splice(idx, 1); }
return items.join(",");
}https://stackoverflow.com/questions/4157780
复制相似问题