remove value from comma separated values string

前端 未结 9 1840
不知归路
不知归路 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:14

    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
    

提交回复
热议问题