我尝试格式化数字,如下所示:123456-12-1234
:
$('.telnumber').keyup(function() {
var foo = $(this).val().split("-").join(""); // remove hyphens
foo = foo.match(new RegExp('.{1,4}$|.{1,2}$|.{1,6}', 'g')).join("-");
$(this).val(foo);
});
然而,它并没有像我期望的那样工作 - 我只是得到了大块的6:http://jsfiddle.net/juspC/892/
我做错了什么?
答案 0 :(得分:1)
如果您可以支持IE9 +,我建议您使用input
event。如果情况并非如此,则应使用库。 Input Mask看起来很不错。
$('form input').on('input', function(e) {
// get just the number
var numeric = this.value.replace(/-/g, '');
// split it by number of numeric characters
split = numeric.match(/^(\d{0,6})(\d{0,2})(\d{0,4})/);
// shift off the whole match
split.shift();
// join back up using dashes and trim trailing and leading dashes
this.value = split.join('-').replace(/^\-+|\-+$/, '');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type='text' maxlength="14"/>
</form>
&#13;
编辑:如果你想在这个东西上获得所有ES6,你也可以对第9行而不是奇怪的正则表达式替换进行以下操作。
this.value = split.filter(a=>a).join('-');