Remove all dots except the first one from a string

前端 未结 12 2590
栀梦
栀梦 2020-12-15 06:34

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

相关标签:
12条回答
  • 2020-12-15 06:44

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

    0 讨论(0)
  • 2020-12-15 06:45

    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, '' );
        });
    }
    
    0 讨论(0)
  • 2020-12-15 06:45

    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, '' );
    }
    
    0 讨论(0)
  • 2020-12-15 06:48

    Based on @Tadek's answer above. This function takes other locales into consideration.


    For example, some locales will use a comma for the decimal separator and a period for the thousand separator (e.g. -451.161,432e-12).

    First we convert anything other than 1) numbers; 2) negative sign; 3) exponent sign into a period ("-451.161.432e-12").

    Next we split by period (["-451", "161", "432e-12"]) and pop out the right-most value ("432e-12"), then join with the rest ("-451161.432e-12")

    (Note that I'm tossing out the thousand separators, but those could easily be added in the join step (.join(','))

    var ensureDecimalSeparatorIsPeriod = function (value) {
        var numericString = value.toString();
        var splitByDecimal = numericString.replace(/[^\d.e-]/g, '.').split('.');
        if (splitByDecimal.length < 2) {
            return numericString;
        }
        var rightOfDecimalPlace = splitByDecimal.pop();
        return splitByDecimal.join('') + '.' + rightOfDecimalPlace;
    };
    
    0 讨论(0)
  • 2020-12-15 06:51

    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;
    };
    
    0 讨论(0)
  • 2020-12-15 06:53

    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,"");
    });
    
    0 讨论(0)
提交回复
热议问题