从字符串中删除除第一个之外的所有点 [英] Remove all dots except the first one from a string
本文介绍了从字符串中删除除第一个之外的所有点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定字符串
'1.2.3.4.5'
我想得到这个输出
'1.2345'
(如果字符串中没有点,则应该保持字符串不变。)
(In case there are no dots in the string, the string should be returned unchanged.)
我写了这个
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/
它但是我希望有一个稍微优雅的解决方案......
It works but I was hoping for a slightly more elegant solution...
推荐答案
如果是浏览器,使用reg exp将会轻松得多支持外观。
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, '' );
});
}
这篇关于从字符串中删除除第一个之外的所有点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文