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
4 Answers 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"
Comments
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.
4 Comments
join to rebuild the string from the arraystr.replace is not mentioned in this answer, and you are providing conflicting specifications in your question and subsequent comments.function removeValue(value, commaDelimitedString)
{
var items = commaDelimitedString.split(/,/);
var idx = items.indexOf(value);
if(idx!=-1) { items.splice(idx, 1); }
return items.join(",");
}
2 Comments
you can use split and merge functions in javascript
:foo:bar:. That has 2 fields if colon-delimited, 3 fields if colon-terminated, and 4 fields if colon-separated. We're programmers: don't get sloppy.