简体   繁体   English

从数组中删除所有出现的字符串

[英]Remove all occurrences of a string from an array

I would like to split an array at all occurences of a string in an array, in Javascript.我想在 Javascript 中的数组中所有出现的字符串处拆分一个数组。 For example:例如:

var array = ["fast", "red", "race"];
var string = "The fast red race car drove fast.";

var replacedArray = [];

I would like end up with replacedArray being equal to: ["The "," car drove ","."]我希望replacedArray等于: ["The "," car drove ","."]

I've looked around for a while, but I can't find anything.我环顾四周,但找不到任何东西。 I assume it would be done with a split() and join() , but I have no idea beyond that.我认为它将通过split()join()来完成,但除此之外我不知道。

How would I go about doing this?我将如何 go 这样做?

So this seems like something fundamental I would try to work out on my own, so I'm not going to be sending any code.所以这似乎是我会尝试自己解决的基本问题,所以我不会发送任何代码。 Instead, I am going to guide you in the direction to which you could solve this problem.相反,我将指导你解决这个问题的方向。 I would use the split() function in order to break up the string (sentence).我会使用 split() function 来分解字符串(句子)。 Then using a nested for loop you loop through the newly created array from the split function and check to see if each element in the array is in that original delimiter array.然后使用嵌套的 for 循环,从拆分 function 中循环遍历新创建的数组,并检查数组中的每个元素是否在原始分隔符数组中。 If it finds that the two elements are the same then you need to remove, or not add to a new array.如果它发现两个元素相同,则需要删除或不添加到新数组中。 Whichever one you like.不管你喜欢哪一个。 From that, you should be able to have an array or some data type in which you have the words that are not in the delimiter array.从此,您应该能够拥有一个数组或某种数据类型,其中包含不在分隔符数组中的单词。

This is an example using the String.prototype.split to separate the sentence into separate tokens based on the word(s) for removal, and then Array.prototype.filter to remove empty / space only strings.这是一个示例,使用String.prototype.split根据要删除的单词将句子分成单独的标记,然后使用Array.prototype.filter删除空/仅空格的字符串。

 const remove = ["fast", "red", "race"]; const string = "The fast red race car drove fast."; const result = string.split(new RegExp(remove.join("|"))).filter(token =>.;token.trim()); console.log(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM