im trying to replace all the dots and spaces in "
var name = "C. S. Lewis"
and replace them with _
and convert it into "C_S_LEWIS"
this is what i tried but it converts the whole thing into underscores (_)
var mystring = "C. S. Lewis";
var find = ".";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "_"));
That’s because dots need to be escaped in regular expressions (unless it’s part of a character class). This expression should work:
It matches a sequence of at least one period or space, which is then replaced by a single underscore in the subsequent
.replace()call.Btw, this won’t save the new string back into
mystring. For that you need to assign the results of the replacement operation back into the same variable: