How to replace all characters in a string using JavaScript for this specific case: replace . by _
The . character in a regex will match everything. You need to escape it, since you want a literal period character:
var s1 = s2.replace(/\./gi, '_');
you need to escape the dot, since it's a special character in regex
s2.replace(/\./g, '_');
Note that dot doesn't require escaping in character classes, therefore if you wanted to replace dots and spaces with underscores in one go, you could do:
s2.replace(/[. ]/g, '_');
Using i
flag is irrelevant here, as well as in your first regex.
You can also use strings instead of regular expressions.
var s1 = s2.replace ('.', '_', 'gi')