我输入的内容需要设置为 xx.xx.xx-xxx.xx
我有以下代码,但直到现在我仍将其格式化为 xx-xx-xx-xx-xx-xx-xx-x
我做错了吗?
任何建议将不胜感激。
代码:
var $form = $( ".commerce-add-to-cart" );
var $input = $form.find(".form-item-field-extra-velden-tkm-0-field-national-reg-num-und-0-value input");
$input.on( "keyup", function( event ) {
var selection = window.getSelection().toString();
if ( selection !== '' ) {
return;
}
if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
return;
}
var $this = $(this);
var input = $this.val();
input = input.replace(/[\W\s\._\-]+/g, '');
var split = 4;
var chunk = [];
for (var i = 0, len = input.length; i < len; i += split) {
split = ( i >= 2 && i <= 9 ) ? 2 : 2;
chunk.push( input.substr( i, split ) );
}
$this.val(function() {
return chunk.join("-").toUpperCase();
});
});
答案 0 :(得分:0)
这是我格式化字符串的方法,它可能不是最佳选择,但效果很好。
let inputString = '01234567890';
let splitIndex = 6;
function format (value) {
let firstPart = splitString(value.substring(0, splitIndex), 2).join('.');
let secondPart = splitString(value.substring(splitIndex), 3).join('.');
return [firstPart, secondPart].join('-');
}
function splitString (str, n) {
let arr = [];
var len;
for(let i = 0, len = str.length; i < len; i += n) {
arr.push(str.substr(i, n))
}
return arr;
}
let formatedInput = format(inputString);
console.log(formatedInput);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
答案 1 :(得分:0)
您可以使用正则表达式替换。您的每个捕获组都以$ x表示,您可以在其中进行格式化。
const inputString = '01234567890';
const formatted = inputString.replace(/(\d{2})(\d{2})(\d{2})(\d{3})(\d{2})/g, "$1.$2.$3-$4.$5");
console.log(formatted);