use*_*159 1 javascript regex jquery
我正在尝试返回逗号分隔的字符串,而不包含以"非"结尾的项目.
资源:
id = '2345,45678,3333non,489,2333non';
Run Code Online (Sandbox Code Playgroud)
预期结果:
id = '2345,45678,489';
Run Code Online (Sandbox Code Playgroud)
我正在使用我在这里找到的代码: 从逗号分隔值字符串中删除值
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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法让线路(values[i] == value)使用通配符?
用途/[^,]*non,|,[^,]*non/g:
id = '2345,45678,3333non,489,2333non';
console.log(
id.replace(/[^,]*non,|,[^,]*non/g, '')
)Run Code Online (Sandbox Code Playgroud)
作为一个功能:
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'))Run Code Online (Sandbox Code Playgroud)