4 ms·
I changed it to: var regex = RegExp(w, 'g'); var s2 = s1.replace(regex, '');
by calibas 7y ago
I 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.