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条回答
贪生不怕死
2楼-- · 2020-02-09 04:00

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,"");
});
查看更多
戒情不戒烟
3楼-- · 2020-02-09 04:00

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;
};
查看更多
ゆ 、 Hurt°
4楼-- · 2020-02-09 04:02

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.

查看更多
我欲成王,谁敢阻挡
5楼-- · 2020-02-09 04:03
var i = s.indexOf(".");
var result = s.substr(0, i+1) + s.substr(i+1).replace(/\./g, "");

Somewhat tricky. Works using the fact that indexOf returns -1 if the item is not found.

查看更多
你好瞎i
6楼-- · 2020-02-09 04:03
var input = '14.1.2';
reversed = input.split("").reverse().join("");
reversed = reversed.replace(\.(?=.*\.), '' );
input = reversed.split("").reverse().join("");
查看更多
Deceive 欺骗
7楼-- · 2020-02-09 04:04

Trying to keep this as short and readable as possible, you can do the following:

JavaScript

var match = string.match(/^[^.]*\.|[^.]+/g);
string = match ? match.join('') : string;

Requires a second line of code, because if match() returns null, we'll get an exception trying to call join() on null. (Improvements welcome.)

Objective-J / Cappuccino (superset of JavaScript)

string = [string.match(/^[^.]*\.|[^.]+/g) componentsJoinedByString:''] || string;

Can do it in a single line, because its selectors (such as componentsJoinedByString:) simply return null when sent to a null value, rather than throwing an exception.

As for the regular expression, I'm matching all substrings consisting of either (a) the start of the string + any potential number of non-dot characters + a dot, or (b) any existing number of non-dot characters. When we join all matches back together, we have essentially removed any dot except the first.

查看更多
登录 后发表回答