Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove value from comma separated values string

Tags:

javascript

csv

I have a csv string like this "1,2,3" and want to be able to remove a desired value from it.

For example if I want to remove the value: 2, the output string should be the following:

"1,3"

I'm using the following code but seems to be ineffective.

var values = selectedvalues.split(",");
            if (values.length > 0) {
                for (var i = 0; i < values.length; i++) {
                    if (values[i] == value) {
                        index = i;
                        break;
                    }
                }
                if (index != -1) {
                    selectedvalues = selectedvalues.substring(0, index + 1) + selectedvalues.substring(index + 3);                    
                }
            }
            else {
                selectedvalues = "";
            }
like image 855
Raúl Roa Avatar asked Aug 20 '09 13:08

Raúl Roa


6 Answers

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.

Thanks to Grant Wagner for pointing out my code mistake and enhancement!

John Resign (jQuery, Mozilla) has a neat article about JavaScript Array Remove which you might find useful.

like image 66
doomspork Avatar answered Nov 20 '22 05:11

doomspork


function removeValue(list, value) {
  return list.replace(new RegExp(",?" + value + ",?"), function(match) {
      var first_comma = match.charAt(0) === ',',
          second_comma;

      if (first_comma &&
          (second_comma = match.charAt(match.length - 1) === ',')) {
        return ',';
      }
      return '';
    });
};


alert(removeValue('1,2,3', '1')); // 2,3
alert(removeValue('1,2,3', '2')); // 1,3
alert(removeValue('1,2,3', '3')); // 1,2
like image 22
yohann richard Avatar answered Nov 20 '22 07:11

yohann richard


values is now an array. So instead of doing the traversing yourself.

Do:

var index = values.indexOf(value);
if(index >= 0) {
    values.splice(index, 1);
}

removing a single object from a given index.

hope this helps

like image 3
Jabezz Avatar answered Nov 20 '22 07:11

Jabezz


Here are 2 possible solutions:

function removeValue(list, value) {
  return list.replace(new RegExp(value + ',?'), '')
}

function removeValue(list, value) {
  list = list.split(',');
  list.splice(list.indexOf(value), 1);
  return list.join(',');
}

removeValue('1,2,3', '2'); // "1,3"

Note that this will only remove first occurrence of a value.

Also note that Array.prototype.indexOf is not part of ECMAScript ed. 3 (it was introduced in JavaScript 1.6 - implemented in all modern implementations except JScript one - and is now codified in ES5).

like image 3
kangax Avatar answered Nov 20 '22 06:11

kangax


// Note that if the source is not a proper CSV string, the function will return a blank string ("").
function removeCsvVal(var source, var toRemove)      //source is a string of comma-seperated values,
{                                                    //toRemove is the CSV to remove all instances of
    var sourceArr = source.split(",");               //Split the CSV's by commas
    var toReturn  = "";                              //Declare the new string we're going to create
    for (var i = 0; i < sourceArr.length; i++)       //Check all of the elements in the array
    {
        if (sourceArr[i] != toRemove)                //If the item is not equal
            toReturn += sourceArr[i] + ",";          //add it to the return string
    }
    return toReturn.substr(0, toReturn.length - 1);  //remove trailing comma
}

To apply it too your var values:

var values = removeVsvVal(selectedvalues, "2");
like image 1
Breakthrough Avatar answered Nov 20 '22 05:11

Breakthrough


guess im too slow but here is what i would do

<script language="javascript"> 
function Remove(value,replaceValue) 
{   var result = ","+value+",";
result = result.replace(","+replaceValue+",",",");
result = result.substr(1,result.length);
result = result.substr(0,result.length-1);
alert(result);
}

Remove("1,2,3",2)
</script>

adding , before and after the string ensure that u only remove the exact string u want

like image 1
Lil'Monkey Avatar answered Nov 20 '22 07:11

Lil'Monkey