Remove all dots except the first one from a string

2020-02-09 03:27发布

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

12条回答
Emotional °昔
2楼-- · 2020-02-09 03:40

This isn't necessarily more elegant, but it's another way to skin the cat:

var process = function (input) {
    var output = input;

    if (typeof input === 'string' && input !== '') {
        input = input.split('.');
        if (input.length > 1) {
            output = [input.shift(), input.join('')].join('.');
        }
    }

    return output;
};
查看更多
3楼-- · 2020-02-09 03:45

Here is another approach:

function process(input) {
    var n = 0;
    return input.replace(/\./g, function() { return n++ > 0 ? '' : '.'; });
}

But one could say that this is based on side effects and therefore not really elegant.

查看更多
▲ chillily
4楼-- · 2020-02-09 03:50

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, '' );
    });
}
查看更多
乱世女痞
5楼-- · 2020-02-09 03:56

You could also do something like this, i also don't know if this is "simpler", but it uses just indexOf, replace and substr.

var str = "7.8.9.2.3";
var strBak = str;

var firstDot = str.indexOf(".");
str = str.replace(/\./g,"");
str = str.substr(0,firstDot)+"."+str.substr(1,str.length-1);

document.write(str);

Shai.

查看更多
倾城 Initia
6楼-- · 2020-02-09 03:59

Not sure what is supposed to happen if "." is the first character, I'd check for -1 in indexOf, also if you use substr once might as well use it twice.

if ( index != -1 ) {
    input = input.substr( 0, index + 1 ) + input.substr(index + 1).replace( /\./g, '' );
}
查看更多
Fickle 薄情
7楼-- · 2020-02-09 03:59

let str = "12.1223....1322311..";

let finStr = str.replace(/(\d*.)(.*)/, '$1') + str.replace(/(\d*.)(.*)/, '$2').replace(/\./g,'');

console.log(finStr)

查看更多
登录 后发表回答