Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

javascript - 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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...