0

I want to add hyphen in phone number when user enters number .

Phone format should be like 111-111-1111.

I have written code but not able to generate pattern.

Little help will highly appreciated.

<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>
dhananjay_shingote
  • 379
  • 1
  • 4
  • 17
  • 1
    `let ele = document.getElementById(element.id);` you don't need this, just use `element` directly. – David says reinstate Monica Jun 09 '19 at 17:11
  • Possible duplicate of [Implement an input with a mask](https://stackoverflow.com/questions/12578507/implement-an-input-with-a-mask) – Nick Jun 09 '19 at 17:15
  • How about `if (/^\w{3}(?:-\w{3})?$/.test(ele.value)) { ele.value += '-'; }`? – melpomene Jun 09 '19 at 17:17
  • Note: this is super annoying unless done perfectly (and nobody does it perfectly). Consider leaving it at ``. – Ry- Jun 09 '19 at 17:39
  • Phone number validation and formatting is notoriously difficult. Best to leave to the experts, like [libphonenumber](https://stackoverflow.com/questions/17928116/libphonenumber-javascript-validating) – Raymond Chen Jun 09 '19 at 18:29
  • Just so you know, I edited my question to give you some refactoring possibilities. – MilesZew Jun 09 '19 at 18:38

1 Answers1

2

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');
MilesZew
  • 442
  • 1
  • 7
  • 18