我想在用户输入number时在电话号码中添加连字符。
电话格式应为111-111-1111。
我已经编写了代码,但无法生成模式。
几乎没有帮助,将不胜感激。
<html>
<head>
<title>Add Hyphen to a text using JavaScript</title>
</head>
<body>
<p>Type some values (numbers or text) in the text box.
The script will automatically add a "hyphen" (-) after every 3rd character.</p>
<p>The onkeyup event calls a JavaScript fuction after you release the key in text box.</p>
<div>
<input type="text" id="tbNum" onkeyup="addHyphen(this)"
placeholder="Type some values here" maxLength="12"/>
</div>
</body>
<script>
function addHyphen (element) {
let ele = document.getElementById(element.id);
ele = ele.value.split('-').join(''); // Remove dash (-) if mistakenly entered.
let finalVal = ele.match(/.{1,4}/g).join('-');
document.getElementById(element.id).value = finalVal;
}
</script>
</html>
答案 0 :(得分:2)
这很混乱,但是您可以使用regex并替换它:
console.log('1111111111'.replace(/(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)/, '$1$2$3-$4$5$6-$7$8$9$10'))
此代码段捕获每个数字,然后使用'$n'
查找第n个数字,并将'-'
插入适当的位置。
请注意,您不能使用/(\d){10}/
或/\d{10}/
,因为每个数字都需要捕获。
考虑所有问题(如评论中所述)<input type="tel"/>
可能是最好的选择。
完整摘要:
<html>
<head>
<title>Add Hyphen to a text using JavaScript</title>
</head>
<body>
<p>Type some values (numbers or text) in the text box.
The script will automatically add a "hyphen" (-) after every 3rd character.</p>
<p>The onkeyup event calls a JavaScript fuction after you release the key in text box.</p>
<div>
<input type="text" id="tbNum" onkeyup="addHyphen(this)"
placeholder="Type some values here" maxLength="10"/>
</div>
</body>
<script>
function addHyphen (element) {
let ele = document.getElementById(element.id);
ele = ele.value.split('-').join(''); // Remove dash (-) if mistakenly entered.
let finalVal = ele.replace(/(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)/, '$1$2$3-$4$5$6-$7$8$9$10')
document.getElementById(element.id).value = finalVal;
}
</script>
</html>
此外,由于正则表达式的性质,连字符仅在文本中包含正确数量的数字时才添加。如果您只想每三个数字添加一个连字符,而不仅仅是在数量正确的情况下添加连字符,请进行以下更改:
ele.replace(/(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)/, '$1$2$3-$4$5$6-$7$8$9$10')
对此:
ele.replace(/(\d)(\d)(\d)(?!$)/g, '$1$2$3-')
最终备注: 您可以重构上面的注释中的一些内容(尽管可能会稍微降低代码的可读性),即更改此内容:
function addHyphen (element) {
let ele = document.getElementById(element.id);
ele = ele.value.split('-').join(''); // Remove dash (-) if mistakenly entered.
let finalVal = ele.replace(/(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)/, '$1$2$3-$4$5$6-$7$8$9$10')
document.getElementById(element.id).value = finalVal;
对此:
const addHyphen = element => element.value = element.value.replace(/([^\d])/g, '').replace(/(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)/, '$1$2$3-$4$5$6-$7$8$9$10');