3 ms·
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.repl
by scottfr 7y 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.
- wvenable 7y agoI may have been using JavaScript's replace method wrong my entire life...
- calibas 7y agoI changed it to: var regex = RegExp(w, 'g'); var s2 = s1.replace(regex, '');
- minitech 7y agoNow 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)
- scottfr 7y agoThat'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.