Šim*_*das 16 javascript string
给出一个字符串
'1.2.3.4.5'
我想得到这个输出
'1.2345'
(如果字符串中没有点,则应该保持字符串不变.)
我写了这个
function process( input ) {
    var index = input.indexOf( '.' );
    if ( index > -1 ) {
        input = input.substr( 0, index + 1 ) + 
                input.slice( index ).replace( /\./g, '' );
    }
    return input;
}
现场演示: http ://jsfiddle.net/EDTNK/1/
它有效,但我希望有一个更优雅的解决方案......
Tad*_*eck 17
有一个非常简短的解决方案(假设input是你的字符串):
var output = input.split('.');
output = output.shift() + '.' + output.join('');
如果input是" 1.2.3.4",那么output将等于" 1.234".
请参阅此jsfiddle以获取证据.当然,如果您认为有必要,可以将其括在函数中.
编辑:
考虑到您的额外要求(如果没有找到点,则不修改输出),解决方案可能如下所示:
var output = input.split('.');
output = output.shift() + (output.length ? '.' + output.join('') : '');
这将留下例如." 1234"(没有找到点)不变.有关更新的代码,请参阅此jsfiddle.
epa*_*llo 10
如果支持的浏览器看起来很糟糕,那么使用reg exp会更容易.
使用正则表达式的一种方法:
function process( str ) {
    return str.replace( /^([^.]*\.)(.*)$/, function ( a, b, c ) { 
        return b + c.replace( /\./g, '' );
    });
}