[英]How to remove a string from an array of strings?
Basically, I have an array of strings基本上,我有一个字符串数组
var array_strings = ['string1', 'string2', 'string3']
And I would like to know using that array, how could I find every piece of a string that contains something from the array array_strings
and remove it.我想知道使用该数组,如何找到包含数组array_strings
中某些内容的字符串的每一部分并将其删除。
For example, If I have the string var hello = 'string1 Hello string2'
例如,如果我有字符串var hello = 'string1 Hello string2'
I would like it to output only Hello
and remove string1
and string2
.我希望它只输出Hello
并删除string1
和string2
。
Iterate over the array and use the string replace
method to remove the strings from the array.遍历数组并使用字符串replace
方法从数组中删除字符串。 We turn the string into a regular expression
through the RegExp
constructor.我们通过RegExp
构造函数将字符串转换为regular expression
。 This will allow for multiple replaces and the use of a variable within our 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));
One possibility would be to join
the array of strings you want to remove by |
一种可能性是join
要删除的字符串数组|
, then construct a regular expression from that, and .replace
with ''
: ,然后构造从正则表达式,以及.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, ''));
If you also want to remove the leading/trailing spaces, then use .trim()
as well.如果您还想删除前导/尾随空格,也可以使用.trim()
。
If you are going to have only words as per your example with no commas/punctuation etc then you could also simply split the string and then Array.filter
it via Array.includes
:如果你将不得不唯一的话,按您的例子,没有逗号/标点符号等,然后你也可以简单地分割字符串,然后Array.filter
通过它Array.includes
:
const str = 'string1 Hello string2 there string3', arr = ['string1', 'string2', 'string3']; console.log(...str.split(' ').filter(x => !arr.includes(x)))
It is a simpler approach in scenario where you do not have complex sentences/string data for which you would need String.replace
via RegEx
etc.在您没有复杂的句子/字符串数据的情况下,这是一种更简单的方法,您需要通过RegEx
等对其进行String.replace
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.