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...
You can try something like this:
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:
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(',')
)There is a pretty short solution (assuming
input
is your string):If
input
is "1.2.3.4
", thenoutput
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:
which will leave eg. "
1234
" (no dot found) unchanged. See this jsfiddle for updated code.Somewhat tricky. Works using the fact that
indexOf
returns -1 if the item is not found.Trying to keep this as short and readable as possible, you can do the following:
JavaScript
Requires a second line of code, because if
match()
returns null, we'll get an exception trying to calljoin()
on null. (Improvements welcome.)Objective-J / Cappuccino (superset of JavaScript)
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.