简体   繁体   中英

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. 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 ","."]

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.

How would I go about doing this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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