移除字符串(如果找到)移除JS中字符串的一部分
Remove strings if found remove a part of the string in JS
我遇到了一个问题。
我有这个:
<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,'');
相关文章:
- 使用递归、Ramda.js和无点样式重构字符串的getPermutations()
- 如何在JS文件中获取资源(.resx)字符串
- 用有限的字符集压缩字符串,然后在JS中解压缩
- node.js将字符串转换为要上传到Web服务器的文件
- 在 JS 中添加字符串之前强制换行
- 从JS中的字符串中读取数字的库
- 将字符串转换为JS对象
- Js char数组将字符串整数视为整数
- 闭包js框架-将ArrayBuffer转换为字符串
- 从字符串JS的末尾提取子字符串
- 替换除匹配字符串JS Regex之外的所有内容
- 在我的情况下,lastindexof和子字符串js混淆
- 如何把空格后的数字在字符串js
- 删除字符串JS最后一个字母之后的所有字符
- 如何删除重复字符形式字符串?- JS
- 字符串.JS格式
- 是否有php字符串/JS警告框的最大行数?
- 清理可搜索的字符串JS
- 忽略字符串- JS - Regex的第一个字符
- 从字符串 JS/jQuery 中删除 HTML 标记