Remove all dots except the first one from a string

You can try something like this:

str = str.replace(/\./,"#").replace(/\./g,"").replace(/#/,".");

But you have to be sure that the character # is not used in the string; or replace it accordingly.

Or this, without the above limitation:

str = str.replace(/^(.*?\.)(.*)$/, function($0, $1, $2) {
  return $1 + $2.replace(/\./g,"");
});

There is a pretty short solution (assuming input is your string):

var output = input.split('.');
output = output.shift() + '.' + output.join('');

If input is "1.2.3.4", then output will be equal to "1.234".

See this jsfiddle for a proof. Of course you can enclose it in a function, if you find it necessary.

EDIT:

Taking into account your additional requirement (to not modify the output if there is no dot found), the solution could look like this:

var output = input.split('.');
output = output.shift() + (output.length ? '.' + output.join('') : '');

which will leave eg. "1234" (no dot found) unchanged. See this jsfiddle for updated code.


It would be a lot easier with reg exp if browsers supported look behinds.

One way with a regular expression:

function process( str ) {
    return str.replace( /^([^.]*\.)(.*)$/, function ( a, b, c ) { 
        return b + c.replace( /\./g, '' );
    });
}