-2

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.

For example, If I have the string var hello = 'string1 Hello string2'

I would like it to output only Hello and remove string1 and string2.

Aiden Kaiser
  • 155
  • 1
  • 9
  • https://stackoverflow.com/questions/5069464/replace-multiple-strings-at-once – Herohtar Dec 04 '18 at 20:32
  • @Herohtar not what I am asking he is using regex – Aiden Kaiser Dec 04 '18 at 20:33
  • He's actually not using regex in the question; however, you have to use the regex version of replace if you want to be able to replace multiple occurances of the string, for example, if you have `hello = 'string1 Hello string2 string1'` – Herohtar Dec 04 '18 at 20:35

3 Answers3

2

Iterate over the array and use the string replace method to remove the strings from the array. We turn the string into a regular expression through the RegExp constructor. 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));
zfrisch
  • 8,474
  • 1
  • 22
  • 34
2

One possibility would be to join the array of strings you want to remove by |, then construct a regular expression from that, and .replace with '':

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

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:

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.

Akrion
  • 18,117
  • 1
  • 34
  • 54