[英]how to remove everything after a particular string from an array of strings in javascript
[英]How to remove a string from an array of strings?
基本上,我有一個字符串數組
var array_strings = ['string1', 'string2', 'string3']
我想知道使用該數組,如何找到包含數組array_strings
中某些內容的字符串的每一部分並將其刪除。
例如,如果我有字符串var hello = 'string1 Hello string2'
我希望它只輸出Hello
並刪除string1
和string2
。
遍歷數組並使用字符串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.