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

Remove a number from a comma separated string while properly removing commas

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

FOR EXAMPLE: Given a string... "1,2,3,4"

I need to be able to remove a given number and the comma after/before depending on if the match is at the end of the string or not.

remove(2) = "1,3,4"

remove(4) = "1,2,3"

Also, I'm using javascript.

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

As jtdubs shows, an easy way is is to use a split function to obtain an array of elements without the commas, remove the required element from the array, and then rebuild the string with a join function.

For javascript something like this might work:

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"

You also need to consider the behavior you want if you have repeats, say the string is "1,2,2,4" and I say "remove(2)" should it remove both instances or just the first? this function will remove only the first instance.