Replacing dots _ using javascript globally?

im trying to replace all dots and spaces in "

var name = "C. S. Lewis"

      

and replace them with _

and convert it to "C_S_LEWIS"

this is what i tried but it converts the whole thing to underscores ( _

)

var mystring = "C. S. Lewis";
var find = ".";
var regex = new RegExp(find, "g");
alert(mystring.replace(regex, "_"));

      

+3


source to share


2 answers


This is because dots must be escaped in regular expressions (unless they are part of a character class). This expression should work:

var regex = /[.\s]+/g;

alert(mystring.replace(regex, '_'))

      

It matches a sequence of at least one period or space, which is then replaced with a single underscore in a subsequent call .replace()

.



Btw, this won't save the newline back to mystring

. To do this, you need to return the results of the replacement operation to the same variable:

mystring = mystring.replace(regex, '_')

      

+4


source


.

means "any character". Use \.

to get a literal dot, which means that in your string regex

you must put \\.

to get a literal underscore followed by a literal dot. But I'm not sure why you are doing the line first - you could just do this:

var find = /\./g;

      



Of course, that's not what you're looking for - you don't want just any period, but just periods followed by spaces. This is different:

var find = /\.\s+/g;

      

0


source







All Articles