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...
This isn't necessarily more elegant, but it's another way to skin the cat:
Here is another approach:
But one could say that this is based on side effects and therefore not really elegant.
It would be a lot easier with reg exp if browsers supported look behinds.
One way with a regular expression:
You could also do something like this, i also don't know if this is "simpler", but it uses just indexOf, replace and substr.
Shai.
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.