从逗号分隔值字符串中删除值

时间:2022-05-02 00:24:49

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

我有一个像这个“1,2,3”的csv字符串,并希望能够从中删除所需的值。

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

例如,如果我想删除值:2,输出字符串应如下所示:

"1,3"

“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 = "";
            }

9 个解决方案

#1


38  

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!

感谢Grant Wagner指出我的代码错误和增强!

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

John Resign(jQuery,Mozilla)有一篇关于JavaScript Array Remove的简洁文章,您可能会发现它很有用。

#2


6  

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

#3


3  

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).

另请注意,Array.prototype.indexOf不是ECMAScript ed的一部分。 3(它是在JavaScript 1.6中引入的 - 在除JScript之外的所有现代实现中实现 - 现在在ES5中编写)。

#4


2  

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

希望这可以帮助

#5


1  

// 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值:

var values = removeVsvVal(selectedvalues, "2");

#6


1  

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

添加,在字符串之前和之后确保你只删除你想要的确切字符串

#7


0  

function process(csv,valueToDelete) {
  var tmp = ","+csv;
  tmp = tmp.replace(","+valueToDelete,"");
  if (tmp.substr(0,1) == ',') tmp = tmp.substr(1);
  return tmp;
}

#8


0  

use splice, pop or shift. depending on your requirement.

使用拼接,弹出或移位。根据您的要求。

You could also have "find" the indexes of items in your array that match by using a function like the one found here : http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have

您还可以使用类似于此处的函数“查找”数组中项目的索引:http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have

var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
//         0/1/2 /3 /4/5 /6 /7     /8  /9/10/11/12/13/14/15/16/17/  18/    19/      20
var thirty=tmp.find(30);             // Returns 9, 14, 17
var thirtyfive=tmp.find('35');       // Returns 18
var thirtyfive=tmp.find(35);         // Returns 15
var haveBlue=tmp.find('blue');       // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/);          // returns 8,20    (first letter starts with b)
var regexp1=tmp.find(/^b/i);         // returns 8,19,20 (same as above but ignore case)

Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}

#9


0  

or

要么

var csv_remove_val = function(s, val, sep) { 
  var sep = sep || ",", a = s.split(sep), val = ""+val, pos;
  while ((pos = a.indexOf(val)) >= 0) a.splice(pos, 1);
  return a.join(sep);
}

#1


38  

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!

感谢Grant Wagner指出我的代码错误和增强!

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

John Resign(jQuery,Mozilla)有一篇关于JavaScript Array Remove的简洁文章,您可能会发现它很有用。

#2


6  

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

#3


3  

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).

另请注意,Array.prototype.indexOf不是ECMAScript ed的一部分。 3(它是在JavaScript 1.6中引入的 - 在除JScript之外的所有现代实现中实现 - 现在在ES5中编写)。

#4


2  

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

希望这可以帮助

#5


1  

// 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值:

var values = removeVsvVal(selectedvalues, "2");

#6


1  

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

添加,在字符串之前和之后确保你只删除你想要的确切字符串

#7


0  

function process(csv,valueToDelete) {
  var tmp = ","+csv;
  tmp = tmp.replace(","+valueToDelete,"");
  if (tmp.substr(0,1) == ',') tmp = tmp.substr(1);
  return tmp;
}

#8


0  

use splice, pop or shift. depending on your requirement.

使用拼接,弹出或移位。根据您的要求。

You could also have "find" the indexes of items in your array that match by using a function like the one found here : http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have

您还可以使用类似于此处的函数“查找”数组中项目的索引:http://www.hunlock.com/blogs/Ten_Javascript_Tools_Everyone_Should_Have

var tmp = [5,9,12,18,56,1,10,42,'blue',30, 7,97,53,33,30,35,27,30,'35','Ball', 'bubble'];
//         0/1/2 /3 /4/5 /6 /7     /8  /9/10/11/12/13/14/15/16/17/  18/    19/      20
var thirty=tmp.find(30);             // Returns 9, 14, 17
var thirtyfive=tmp.find('35');       // Returns 18
var thirtyfive=tmp.find(35);         // Returns 15
var haveBlue=tmp.find('blue');       // Returns 8
var notFound=tmp.find('not there!'); // Returns false
var regexp1=tmp.find(/^b/);          // returns 8,20    (first letter starts with b)
var regexp1=tmp.find(/^b/i);         // returns 8,19,20 (same as above but ignore case)

Array.prototype.find = function(searchStr) {
  var returnArray = false;
  for (i=0; i<this.length; i++) {
    if (typeof(searchStr) == 'function') {
      if (searchStr.test(this[i])) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    } else {
      if (this[i]===searchStr) {
        if (!returnArray) { returnArray = [] }
        returnArray.push(i);
      }
    }
  }
  return returnArray;
}

#9


0  

or

要么

var csv_remove_val = function(s, val, sep) { 
  var sep = sep || ",", a = s.split(sep), val = ""+val, pos;
  while ((pos = a.indexOf(val)) >= 0) a.splice(pos, 1);
  return a.join(sep);
}