I have an array of strings and a dynamically generated variable x
. What I want to do is remove all occurrences in variable x
if they are found in the array. Check below to better understand my question.
NOTE: The array is expected to contain a lot of elements so the more efficient the code the better. Also, there might be multiple occurrences of words and they all must be removed if found in myArr
//expected to contain a lot of elements
myArr = ["test", "green", "blah", "foo", "bar"]
//dynamic variable
x = "this is my test string with color green"
//dumb approch
x = x.replaceAll("test", "").replaceAll("green", "").replaceAll("blah", "").replaceAll("foo", "").replaceAll("bar", "")
//expected result is the x string with the words inside myArr removed
console.log(x)
2
Answers
You could use regular expressions:
Code explanation:
map
function is used to escape any special regex characters in the words.\b
in the regex ensures that only whole words are matched (avoids partial matches).gi
flags make the regex global (affects all occurrences) and case-insensitive.replace
method then replaces all occurrences of the matched words with an empty string.Edit
If your array elements contain brackets and parenthesis you need to include parenthesis and brackets in the escaping logic. Additionally
'\b'
word boundary might not work as expected so you might need to use a different approach to prevent partial matches.Edit 2
Another way to solve your problem is to split your string into words and filter out the words that are in your array.
this is also way easier to read and understand.
This is one way to do it. I don’t know what efficient means in the context. I am using every to iterate over the string and remove each element one by one.