Search code examples
javascriptwebsplitvisual-web-developer

javascript split string selected text remove


How do I delete a fragmented of text from within a string with javascript

Example String:

var start = "World,Book,Pencil,Door";

Now, when I select any of the selected values: "World", I want the result to be "Book,Pencil,Door".

// result = "Book,Pencil,Door";

Solution

  • If you are asking how to remove a value from a comma separated string, try this ...

    var removeValue = function(list, value, separator) {
      separator = separator || ",";
      var values = list.split(separator);
      for(var i=0; i<values.length; i++) {
        if(values[i]===value) {
          values.splice(i, 1);
          return values.join(separator);
        }
      }
      return list;
    }
    

    If the value you're looking for is found, it's removed, and a new comma delimited list returned. If it is not found, the old list is returned.

    Another version ... using indexOf

    var removeValue = function(list, value, separator) {
      separator = separator || ",";
      var values = list.split(separator);
      var index = values.indexOf(value);
      if(index >= 0) {
        values.splice(index, 1);
        return values.join(separator);
      } else {
        return list;
      }
    }
    

    Basically, with either function you send the list ("World,Book,Pencil,Door") as a string, the value to remove ("World") as another string and what the separator is ("," for comma ... however, comma is also the default so can be left off). If the value to remove does not exist in the list, it will return the list. If it is in the list, it will be removed.

    Example 1:

    var final = removeValue("World,Book,Pencil,Door", "World");
    // final = "Book,Pencil,Door"
    

    Example 2:

    var final = removeValue("World,Book,Pencil,Door", "House");
    // final = "World,Book,Pencil,Door"
    

    Example 3:

    var final = removeValue("World|Book|Pencil|Door", "World", "|");
    // final = "Book,Pencil,Door"
    

    UPDATE:

    jsFiddle: http://jsfiddle.net/rfornal/96awa2ht/