Hacker News new | ask | show | jobs
by calibas 2451 days ago
I changed it to:

    var regex = RegExp(w, 'g');
    var s2 = s1.replace(regex, '');
2 comments

Now it doesn’t work if the string you want to replace has any regex special characters. One JS idiom for replace-all is

  str.split(before).join(after)
That's also problematic. If w includes characters that have special meaning in a regex (e.g. a period), this will cause issues.

You could try to escape those special characters but that is potentially error prone.

For an arbitrary w, one approach is something kind of awful like:

  let s2 = s1;
  while (s2.includes(w)) {
    s2 = s2.replace(w, '')
  }
Edit: minitech's solution is better.