skip to Main Content

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


  1. You could use regular expressions:

    // Array containing the words to remove
    const myArr = ["test", "green", "blah", "foo", "bar"];
    
    // Dynamic variable
    let x = "this is my test string with color green";
    
    // Create a regular expression that matches any word in myArr, including optional spaces around the word
    const regexPattern = myArr.map(word => `\s*${word.replace(/[-/\^$*+?.()|[]{}]/g, '\$&')}\s*`).join('|');
    const regex = new RegExp(`(${regexPattern})`, 'gi');
    
    // Replace all occurrences of the words in x, including surrounding spaces
    x = x.replace(regex, ' ').trim();
    
    // Replace multiple spaces with a single space
    x = x.replace(/s+/g, ' ');
    
    // Log the result
    console.log(x);

    Code explanation:

    • The 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).
    • The gi flags make the regex global (affects all occurrences) and case-insensitive.
    • The 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.

    // Array containing the words to remove
    const myArr = ["(test)", "green", "blah", "foo", "bar"];
    
    // Dynamic variable
    let x = "this is my (test) string with color green";
    
    // Function to escape special characters
    const escapeRegExp = (word) => word.replace(/[-/\^$*+?.()|[]{}]/g, '\$&');
    
    // Create a regular expression that matches any word in myArr
    const regexPattern = myArr.map(escapeRegExp).join('|');
    const regex = new RegExp(`(?:^|\s)(${regexPattern})(?:$|\s)`, 'gi');
    
    // Replace all occurrences of the words in x
    x = x.replace(regex, ' ').trim();
    
    // Log the result
    console.log(x);

    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.

    // Split the string into words
    let words = x.split(/s+/);
    
    // Filter out words that are in myArr
    words = words.filter(word => !myArr.includes(word));
    
    // Join the words back into a string
    x = words.join(' ');
    

    this is also way easier to read and understand.

    Login or Signup to reply.
  2. 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.

    //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 
    myArr.every((y)=>{
      x = x.replace(y+' ', '');
    })
    console.log(x)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search