Skip to content Skip to sidebar Skip to footer

String Manipulation - Removing An Element From A List

I have a comma separated list of values, and I need to remove the one that is equal to a certain value. myList = '10,20,30'; myList.remove(20); // === '10,30'

Solution 1:

I'm dashing off, but the component parts of the solution will probably be:

  • String#split, which splits a string into an array based on a delimiter.
  • Array#indexOf, which finds an entry in an array (some older browsers may not have it; on those, you'll have to do a loop).
  • Array#splice, which (amongst other things) removes entries from an array.
  • Array#join, which joins an array into a string using a given delimiter.

...possibly with something mixed in there to deal with stray spaces, if they're a possibility.

Or of course, you could just put commas at either end and then search for ",20," with String#indexOf and use String#substring to grab the bits in front of and behind it. But what fun is that. ;-) (And it seems a bit fragile.)

Solution 2:

Here is some tested and jslinted code that does what you're asking for.

if (!String.prototype.removeListItem) {
   String.prototype.removeListItem = function(value, delimiter) {
      delimiter = delimiter || ',';
      value = value.toString();
      var arr = this.split(delimiter),
         index = arr.indexOf(value);
      while (index >= 0) {
         arr.splice(index, 1);
         index = arr.indexOf(value);
      }
      return arr.join(delimiter);
   };
}

alert('10,20,30,120,200'.removeListItem(20));
// yields '10,30,120,200'

However, I question why you would do this. Arrays should be stored in array objects, not in string literals. If you need to display the list, then convert to a delimited list at display time. If your input is a string, then split it at input time and keep it internally as an array. I really strongly believe this is the best practice for you and in the long run you will have much easier to maintain code that is much easier to understand.

Solution 3:

var myArray = myList.split(',');
myArray.splice(1,1); // Remove one element at index 1, which is 20 in your example
myList = myArray.toString();

Solution 4:

A few people almost had replace working.

var lists = ['20', '10,20', '20,30', '10,20,30', '120,200,2020'];
for (var i=0; i<lists.length; ++i) {
    lists[i] = lists[i].replace(/(^|,)20,|(^|,)20$/,'$1');
}

Result:

["", "10", "30", "10,30", "120,200,2020"]

Solution 5:

Split the string to give you an array. Once you have it in an array, remove the element you need removed. Then output the string again.

Or you could find and replace '20', with ''.

Post a Comment for "String Manipulation - Removing An Element From A List"