Hacker News new | ask | show | jobs
by scottfr 2454 days ago
There are also issues with the JS examples.

For example:

"""

Remove all occurrences of string w from string s1, and store the result in s2.

var s2 = s1.replace(w, '');

"""

Since w is a string, this will only replace the first occurrence, not all occurrences.

2 comments

I may have been using JavaScript's replace method wrong my entire life...
I changed it to:

    var regex = RegExp(w, 'g');
    var s2 = s1.replace(regex, '');
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.