Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all dots except the first one from a string

Given a string

'1.2.3.4.5'

I would like to get this output

'1.2345'

(In case there are no dots in the string, the string should be returned unchanged.)

I wrote this

function process( input ) {
    var index = input.indexOf( '.' );

    if ( index > -1 ) {
        input = input.substr( 0, index + 1 ) + 
                input.slice( index ).replace( /\./g, '' );
    }

    return input;
}

Live demo: http://jsfiddle.net/EDTNK/1/

It works but I was hoping for a slightly more elegant solution...

like image 711
Šime Vidas Avatar asked Nov 15 '11 17:11

Šime Vidas


2 Answers

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.

like image 160
Tadeck Avatar answered Oct 19 '22 10:10

Tadeck


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, '' );
    });
}
like image 23
epascarello Avatar answered Oct 19 '22 09:10

epascarello