How to replace all dots in a string using JavaScript

How to replace all dots in a string using JavaScript

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

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

One more solution which is easy to understand 🙂

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

How to replace all dots in a string using JavaScript

/**
 * 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.

Leave a Reply

Your email address will not be published. Required fields are marked *