如果找到删除字符串在JS中删除字符串的一部分

时间:2015-04-02 20:07:58

标签: javascript

我遇到了问题。

我有这个:

<input type="hidden" name="Boss" id="Boss" value="8,116,167,198,139,203,158,170,">

实际上我在js中有这段代码:

// On click on element with class .Boss
$("form").on("click", ".Boss", function(event){
  var clickedId = $(this).attr('value')+','; // give me 8,
  var locationBtn = $('#Boss'); // Select the input
  var locationBtnValue = $('#Boss').val(); // Take the select value

  if(locationBtnValue.toString().indexOf(clickedId) == -1) { locationBtn.val(locationBtnValue + clickedId); }
  else { locationBtn.val(locationBtnValue.replace(clickedId,'')); }
});

我的问题是:如果想要决定删除8我的javascript,请不要删除项目8,,但第一次出现它会在我的字符串中找到,所以8,116,167,19 ** 8, ** 139203158170 ,.所以它打破了我的其他项目......

如何做到不破坏它?

感谢。

3 个答案:

答案 0 :(得分:1)

我不知道你的最终结果是什么,但我认为你希望它是116,167,198,139,203,158,170,在这种情况下你可以拆分和过滤数组以摆脱价值。

var str = "8,116,167,198,139,203,158,170,";  //the input
var updated = str.split(",")   //turn it into an array
                 .filter(function (val) { //loop through all the elements applying this function
                     return val!=="8"; //keep the item if the index does not match the item
                 }
              ).join(",");  //turn array back into a string

答案 1 :(得分:0)

这是replace传递字符串时所做的事情,它取代了第一次出现。

您需要使用全局修饰符传递正则表达式,如此

locationBtnValue.replace(/8,/g,'')

您可以使用RegExp构造函数执行相同的操作,并使用您拥有的字符串创建正则表达式

var clickedId = $(this).val() + ',';

var regex = new RegExp(clickedId, "g");

locationBtnValue.replace(regex,'');

答案 2 :(得分:0)

要保持一致的一种方法是将其拆分为数组然后删除出现。

// On click on element with class .Boss
$("form").on("click", ".Boss", function(event) {
  var clickedId = $(this).attr('value'); // give me 8
  var locationBtn = $('#Boss'); // Select the input
  var locationBtnValue = locationBtn.val(); // Take the select value
  var ids = locationBtnValue.split(','); //split into an array

  var index = ids.indexOf(clickedId); //index of clickedId inside ids

  if(index > -1) { //found
      ids = ids.splice(index, 1); //remove from ids

  } else {
      ids.push(clickedId); //add to ids
  }

  locationBtn.val(ids.join(','));      

});
相关问题