views:

65

answers:

4

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 _, 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?

+11  A: 

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, '_');
JacobM
+5  A: 

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.

SilentGhost
+3  A: 

You can also use strings instead of regular expressions.

var s1 = s2.replace ('.', '_', 'gi')
dbrown0708
+1 Good point - regex is overkill here. (cue the J.Z. quote in 3...2...1...)
Piskvor
The 3rd parameter is not standard. Not all browser will support it. See this https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/String/replace
HoLyVieR
A: 

There is also this that works well too :

var s1 = s2.split(".").join("_"); // Replace . by _ //
HoLyVieR
that's a very strange approach
SilentGhost
well, it's the only one that doesn't require RegExp at all.
HoLyVieR