admin管理员组文章数量:1410674
I'm trying to return a ma separated string without the items that end in 'non'.
Source:
id = '2345,45678,3333non,489,2333non';
Expected Result:
id = '2345,45678,489';
I'm using code that I found here: remove value from ma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
Is there a way to make the line (values[i] == value)
use a wildcard?
I'm trying to return a ma separated string without the items that end in 'non'.
Source:
id = '2345,45678,3333non,489,2333non';
Expected Result:
id = '2345,45678,489';
I'm using code that I found here: remove value from ma separated values string
var removeValue = function(list, value, separator) {
separator = separator || ",";
var values = list.split(separator);
for (var i = 0; i < values.length; i++) {
if (values[i] == value) {
values.splice(i, 1);
return values.join(separator);
}
}
return list;
}
Is there a way to make the line (values[i] == value)
use a wildcard?
3 Answers
Reset to default 7Use /[^,]*non,|,[^,]*non/g
:
id = '2345,45678,3333non,489,2333non';
console.log(
id.replace(/[^,]*non,|,[^,]*non/g, '')
)
As a function:
id = '2345,45678,3333non,489,2333non';
removeItem = function(s, ends) {
pat = new RegExp(`[^,]*${ends},|,[^,]*${ends}`, 'g')
return s.replace(pat, '')
}
console.log(removeItem(id, 'non'))
You can also get that result without using regex
like this:
var id = '2345,45678,3333non,489,2333non';
var resArray = id.split(',').filter((item) => item.indexOf('non') === -1);
var resString = resArray.toString();
console.log(resString);
If you do not want to use arrow funtion:
var id = '2345,45678,3333non,489,2333non';
var resArray = id.split(',').filter(function(item) {
return item.indexOf('non') === -1;
});
var resString = resArray.toString();
console.log(resString);
You don't need regex for this. Just split on ,
and filter the array for all elements that don't end in non
.
var id = '2345,45678,3333non,489,2333non'
console.log(id.split(',').filter(x => !x.endsWith('non')).join(','))
Thanks to Nope for pointing out that endsWith()
will not work in IE. To get around this issue, see Mozilla's Polyfill for endsWith
or JavaScript endsWith is not working in IEv10.
本文标签: jqueryRemove a value in a string with a wildcard using JavascriptStack Overflow
版权声明:本文标题:jquery - Remove a value in a string with a wildcard using Javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744981885a2635864.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论