It's fairly messy, but you could use regex and replace in order to do it:
console.log('1111111111'.replace(/(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)/, '$1$2$3-$4$5$6-$7$8$9$10'))
This code snippet captures each number and then uses '$n'
to find nth number and insert '-'
in the appropriate places.
Note that you couldn't use /(\d){10}/
or /\d{10}/
because each number needs to be captured.
All things considered (as mentioned in the comments) <input type="tel"/>
is probably the best way to go.
Full snippet:
<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>
Also, because of the nature of the regular expression the hyphens are only added when the correct amount of numbers are in the text. If you just want to add the hyphens every three numbers, and not just when there are the correct amount of numbers, change this:
ele.replace(/(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)(\d)/, '$1$2$3-$4$5$6-$7$8$9$10')
to this:
ele.replace(/(\d)(\d)(\d)(?!$)/g, '$1$2$3-')
Final note:
There are a few things that you could refactor mentioned in the comments above (although it may slightly decrease you code readability), namely changing this:
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;
to this:
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');