簡體   English   中英

如何從字符串數組中刪除字符串?

[英]How to remove a string from an array of strings?

基本上,我有一個字符串數組

var array_strings = ['string1', 'string2', 'string3']

我想知道使用該數組,如何找到包含數組array_strings中某些內容的字符串的每一部分並將其刪除。

例如,如果我有字符串var hello = 'string1 Hello string2'

我希望它只輸出Hello並刪除string1string2

遍歷數組並使用字符串replace方法從數組中刪除字符串。 我們通過RegExp構造函數將字符串轉換為regular expression 這將允許多次替換和在我們的表達式中使用變量。

 var array_strings = ['string1', 'string2', 'string3'], str = "string1 hello string2", printStr = (str, removables) => { for (let removable of removables) { let re_removable = new RegExp(removable,"g"); str = str.replace(re_removable, "").trim(); } return str; }; console.log(printStr(str, array_strings));

一種可能性是join要刪除的字符串數組| ,然后構造從正則表達式,以及.replace''

 const array_strings = ['string1', 'string2', 'string3']; const pattern = new RegExp(array_strings.join('|'), 'g'); const hello = 'string1 Hello string2'; console.log(hello.replace(pattern, ''));

如果您還想刪除前導/尾隨空格,也可以使用.trim()

如果你將不得不唯一的話,按您的例子,沒有逗號/標點符號等,然后你也可以簡單地分割字符串,然后Array.filter通過它Array.includes

 const str = 'string1 Hello string2 there string3', arr = ['string1', 'string2', 'string3']; console.log(...str.split(' ').filter(x => !arr.includes(x)))

在您沒有復雜的句子/字符串數據的情況下,這是一種更簡單的方法,您需要通過RegEx等對其進行String.replace

暫無
暫無

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

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