我从用户那里收到一个澳大利亚电话号码作为文字输入。该字符串长度为10个字符,以04开头。我想在用户输入时拆分字符串,结果如0411 111 111.
我目前的解决方案是value.toString().replace(/^(04\d{2})(\d{3})(\d{3})$/, $1 $2 $3)
此解决方案正确分割字符串,但仅限于用户输入了整个10个字符。我希望它在输入前4个字符后开始分割,即0411 1等。
答案 0 :(得分:0)
这是一个适用于您的确切用例的衬垫:
var results = "0411111111".split(/(?=\d{6}$)|(?=\d{3}$)/);
console.log(results);

我们可能会将您的字符串拆分为正则表达式,该正则表达式指向4位数后的点和7位数后的点。
答案 1 :(得分:0)
考虑下面的内容,检查当前输入的手机号码的长度,然后根据长度应用不同的正则表达式:
var mobileInput = document.getElementById('mobile');
mobileInput.addEventListener('keyup', foo);
function foo() {
var unformatted = mobileInput.value;
var pattern, replacer;
if (unformatted.length < 5) {
pattern = /(04\d{2})/;
replacer = '$1 ';
} else if (unformatted.length < 9) {
pattern = /(04\d{2})\s{1}(\d{3})/;
replacer = '$1 $2 ';
} else {
pattern = /^(04\d{2})(\d{3})(\d{3})$/;
replacer = '$1 $2 $3';
}
var formatted = unformatted.replace(pattern, replacer);
mobileInput.value = formatted;
}
&#13;
<input type="text" id="mobile" />
&#13;
答案 2 :(得分:0)
我已经设法提出了一些解决方案。这不是我的目标,但它确实起到了作用。
value.toString()
.replace(/^(04\d{2})(\d{3})(\d{3})$/, $1 $2 $3)
.replace(/[\s-]+$/, "")
这会消除每个按键上的空白区域(每次调用正则表达式时)并重新格式化。
答案 3 :(得分:0)
这是我的解决方案:
代码:
document.getElementById("phone").addEventListener("input", function() {
var matches = this.value.replace(/ /g, "").match(/^(04\d{2})(\d{3})?(\d{3})?(\d*?)$/);
this.value = matches && matches.length > 2 ?
matches.slice(1, matches.length - 1).join(" ")
+ (matches[matches.length - 1] || "")
: this.value;
});
&#13;
<input id="phone" maxlength="12">
&#13;
答案 4 :(得分:0)
我可能会这样做:
let phone = document.getElementById('phone');
phone.addEventListener('keyup', evt => {
// get value, removing anything that isn't a number
let text = phone.value.replace(/\D/g, '');
// turn it into an array
text = text.split('');
// create a new array containing each group of digits, separated by spaces
let out = [...text.slice(0, 4), ' ', ...text.slice(4, 7), ' ', ...text.slice(7, 10)];
// turn it back into a string, remove any trailing spaces
phone.value = out.join('').trim();
}, false);
&#13;
<input id="phone">
&#13;