How to replace all characters in a string using JavaScript for this specific case: replace . by _
The following statement in JavaScript works as expected:
var s1 = s2.replace(/ /gi, '_'); //replace all spaces by the character _
However, to replace all occurrences of the character . by the character开发者_JS百科 _, I have:
var s1 = s2.replace(/./gi, '_');
But the result is a string entirely filled with the character _
Why and how to replace . by _ using JavaScript?
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')
There is also this that works well too :
var s1 = s2.split(".").join("_"); // Replace . by _ //
if need replace " to backspace with " value.replace(/"/g, '\"')
精彩评论