remove value from comma separated values string

前端 未结 9 1843
不知归路
不知归路 2020-12-30 05:27

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

9条回答
  •  醉酒成梦
    2020-12-30 06:18

    // 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");
    

提交回复
热议问题