javascripts regular expression
I have this string 1,2,3,4,5
and say i remove 1 then it 开发者_开发知识库becomes ,2,3,4,5 or 1,2,,4,5
how do I remove "1," or any number from the list and replace those extra commas and also keep in mind the last number "5" doesnt have a comma.
I can use the string replace javascript function , I am more concerned with the last number
example if i remove 5 it should show as 1,2,3,4
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"
Or treat the string as an array, with
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"
Don't use regular expression. Use arrays. You can split()
your string into an array on the comma, then remove the elements as needed. You can then use join()
to put them back together as a string.
function removeValue(value, commaDelimitedString)
{
var items = commaDelimitedString.split(/,/);
var idx = items.indexOf(value);
if(idx!=-1) { items.splice(idx, 1); }
return items.join(",");
}
you can use split and merge functions in javascript
精彩评论