簡體   English   中英

使用Javascript使用通配符刪除字符串中的值

[英]Remove a value in a string with a wildcard using Javascript

我試圖返回一個逗號分隔的字符串,而沒有以“ non”結尾的項目。

資源:

id = '2345,45678,3333non,489,2333non';  

預期結果:

id = '2345,45678,489'; 

我正在使用在這里找到的代碼: 從逗號分隔的值字符串中刪除值

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;
}

有沒有辦法使行(values[i] == value)使用通配符?

使用/[^,]*non,|,[^,]*non/g

 id = '2345,45678,3333non,489,2333non'; console.log( id.replace(/[^,]*non,|,[^,]*non/g, '') ) 


作為功​​能:

 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')) 

您也可以在不使用regex情況下獲得該結果,如下所示:

 var id = '2345,45678,3333non,489,2333non'; var resArray = id.split(',').filter((item) => item.indexOf('non') === -1); var resString = resArray.toString(); console.log(resString); 

如果您不想使用箭頭功能:

 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); 

您不需要正則表達式。 只需拆分一下,然后對並非以non結尾的所有元素過濾數組。

 var id = '2345,45678,3333non,489,2333non' console.log(id.split(',').filter(x => !x.endsWith('non')).join(',')) 

感謝Nope指出endsWith()在IE中不起作用。 要解決此問題,請參閱Mozilla的Polyfill for endsWithJavaScript endsWith在IEv10中不起作用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM