How to replace all dots in a string using JavaScript

How to replace all dots in a string using JavaScript

I want to replace all the occurrences of a dot(.) in a JavaScript string
For example, I have:
var mystring = ‘okay.this.is.a.string’;

I want to get: okay this is a string.
So far I tried:
mystring.replace(/./g,’ ‘)

but this ends up with all the string replaced to spaces.

Solutions/Answers:

Solution 1:

You need to escape the . because it has the meaning of “an arbitrary character” in a regular expression.

mystring = mystring.replace(/\./g,' ')

Solution 2:

One more solution which is easy to understand 🙂

var newstring = mystring.split('.').join(' ');

Solution 3:

/**
 * ReplaceAll by Fagner Brack (MIT Licensed)
 * Replaces all occurrences of a substring in a string
 */
String.prototype.replaceAll = function( token, newToken, ignoreCase ) {
    var _token;
    var str = this + "";
    var i = -1;

    if ( typeof token === "string" ) {

        if ( ignoreCase ) {

            _token = token.toLowerCase();

            while( (
                i = str.toLowerCase().indexOf(
                    _token, i >= 0 ? i + newToken.length : 0
                ) ) !== -1
            ) {
                str = str.substring( 0, i ) +
                    newToken +
                    str.substring( i + token.length );
            }

        } else {
            return this.split( token ).join( newToken );
        }

    }
return str;
};

alert('okay.this.is.a.string'.replaceAll('.', ' '));

Faster than using regex…

EDIT:
Maybe at the time I did this code I did not used jsperf. But in the end such discussion is totally pointless, the performance difference is not worth the legibility of the code in the real world, so my answer is still valid, even if the performance differs from the regex approach.

EDIT2:
I have created a lib that allows you to do this using a fluent interface:

replace('.').from('okay.this.is.a.string').with(' ');

See https://github.com/FagnerMartinsBrack/str-replace.

Solution 4:

str.replace(new RegExp(".","gm")," ")

Solution 5:

For this simple scenario, i would also recommend to use the methods that comes build-in in javascript.

You could try this :

"okay.this.is.a.string".split(".").join("")

Greetings

Solution 6:

I add double backslash to the dot to make it work. Cheer.

var st = "okay.this.is.a.string";
var Re = new RegExp("\\.","g");
st = st.replace(Re," ");
alert(st);