Javascript 删除字符串(如果找到)删除JS中字符串的一部分
我面临一个问题 我有这个:Javascript 删除字符串(如果找到)删除JS中字符串的一部分,javascript,Javascript,我面临一个问题 我有这个: <input type="hidden" name="Boss" id="Boss" value="8,116,167,198,139,203,158,170,"> 我的问题是:如果想要删除8MyJavaScript,不要删除8,,但它会在我的字符串中找到第一个匹配项,所以8116167,19**8,**139203158170,。所以它打破了我的另一个项目 我怎样才能使它不坏呢 谢谢。这就是replace所做的。当您传递一个字符串时,它将替换第一个出现
<input type="hidden" name="Boss" id="Boss" value="8,116,167,198,139,203,158,170,">
我的问题是:如果想要删除8
MyJavaScript,不要删除8,
,但它会在我的字符串中找到第一个匹配项,所以8116167,19**8,**139203158170,。所以它打破了我的另一个项目
我怎样才能使它不坏呢
谢谢。这就是
replace
所做的。当您传递一个字符串时,它将替换第一个出现的字符串
您需要传递一个带有全局修饰符的正则表达式,如下所示
locationBtnValue.replace(/8,/g,'')
您可以对RegExp构造函数执行相同的操作,并从您拥有的字符串创建正则表达式
var clickedId = $(this).val() + ',';
var regex = new RegExp(clickedId, "g");
locationBtnValue.replace(regex,'');
保持一致性的一种方法是将其拆分为一个数组,然后删除该事件
// 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(','));
});
我不知道您的最终结果是什么,但我认为您希望它是
116167198139203158170,
在这种情况下,您可以拆分并过滤数组以除去值
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
我不清楚你的最终结果。什么是初始输入,什么是最终输出?您好,谢谢您的想法,但如果我单击它增益,它不会保留旧数据。我刚刚点击了当前的一个。
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