最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Remove a value in a string with a wildcard using Javascript - Stack Overflow

programmeradmin2浏览0评论

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?

Share Improve this question edited Mar 29, 2018 at 13:54 Nope 22.3k8 gold badges49 silver badges73 bronze badges asked Mar 29, 2018 at 13:45 BillBill 1,4872 gold badges34 silver badges66 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 7

Use /[^,]*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.

发布评论

评论列表(0)

  1. 暂无评论