移除字符串(如果找到)移除JS中字符串的一部分

Remove strings if found remove a part of the string in JS

本文关键字:字符串 JS 移除 一部分 如果      更新时间:2023-09-26

我遇到了一个问题。

我有这个:

<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,项,而是删除它将在我的字符串中找到的第一个项目,因此8116167,19**8,**139203158170,。所以它打碎了我的另一件物品。。。

我怎样才能使它不坏呢?

谢谢。

我不知道你的最终结果是什么,但我认为你希望它是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

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

// 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(','));      
});

replace就是这样做的,当您向它传递字符串时,它会替换第一个出现的字符串。

你需要给它传递一个带有全局修饰符的正则表达式,比如这个

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

您可以使用RegExp构造函数做同样的事情,并从具有的字符串中创建一个正则表达式

var clickedId = $(this).val() + ',';
var regex = new RegExp(clickedId, "g");
locationBtnValue.replace(regex,'');