0

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

9

4 Answers 4

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"
0
2

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
  • +1 - though you should mention join to rebuild the string from the array
    – jball
    Commented Nov 11, 2010 at 18:16
  • var str = '1,2,3,4,5'; str = str.replace('1,', ''); I am trying to remove any of the numbers but this fails when you try to replace "5" str = str.replace('5,', '');
    – user244394
    Commented Nov 11, 2010 at 18:23
  • @user244394 str.replace is not mentioned in this answer, and you are providing conflicting specifications in your question and subsequent comments.
    – jball
    Commented Nov 11, 2010 at 18:26
  • I was trying couple thing split and replace
    – user244394
    Commented Nov 11, 2010 at 18:36
1
function removeValue(value, commaDelimitedString)
{
    var items = commaDelimitedString.split(/,/);
    var idx = items.indexOf(value);
    if(idx!=-1) { items.splice(idx, 1); }
    return items.join(",");
}
2
  • +1 nice function. I guess not as pretty as KennyTM though ;) Commented Nov 11, 2010 at 18:54
  • @Jason McCreary, Thanks, though to be fair, I voted for KennyTM's as well :)
    – jball
    Commented Nov 11, 2010 at 21:28
0

you can use split and merge functions in javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.