0

Hey I have a input where the user enters his social security number. To make the input more readable I want to insert a whitespace after the first 4 characters of the string. The social security number itself is 10 numbers long. So the result should looke like: 1234 567890. I only found solutions where a whitespace every 4 characters is inserted but no example which is similar to this. Has someone an idea how to solve this?

<input type="text" maxlength="10" @keyup="insertWhitespace()"/>
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Does this answer your question? [How to insert space every 4 characters for IBAN registering?](https://stackoverflow.com/questions/17260238/how-to-insert-space-every-4-characters-for-iban-registering) – RïshïKêsh Kümar Sep 20 '22 at 10:22

3 Answers3

2

You can do this with the use of Regular Expression + HTML DOM Element addEventListener().

Reference Website For "Regular Expression": https://regexr.com/

With the help of a regular expression is a sequence of characters that specifies a search pattern in text or strings.

document.getElementById('example').addEventListener('input', function (e) {
  e.target.value = e.target.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim();
});
<input id="example" maxlength="11" name="example" />
Martijn
  • 15,791
  • 4
  • 36
  • 68
RïshïKêsh Kümar
  • 4,734
  • 1
  • 24
  • 36
  • @FloHaberfellner Welcome :), you can read about Regular Expression, and how it exactly works. on a given website. – RïshïKêsh Kümar Sep 20 '22 at 10:36
  • 2
    @Martijn Dear First read the user question clearly, they want to insert whitespace after the first 4 characters of the string. So the result should look like: 1234 567890, they don't want white space after every 4 characters just read the question once again. – RïshïKêsh Kümar Sep 20 '22 at 11:12
0

Here is the solution (Javascript) to your problem:

The code below reads the input value and remove alphabets and then replaces the digit value with the appropriate space character only once as expected after 4 digits.

function insertWhitespace() {
 document.getElementById('myElement').value = document.getElementById('myElement').value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/, '$1 ').trim()
}
<input id="myElement" maxlength="11" onkeyup="insertWhitespace()" />
kavigun
  • 2,219
  • 2
  • 14
  • 33
0

I think you should make your max length to 11 because white space also counts and try it with the following code

const ssn =  document.querySelector("selector");
ssn.addEventListener("keyup",(e) => {
  if(e.target.value.length === 4){
    ssn.value += " "
  }
})
Abbas Shaikh
  • 304
  • 1
  • 9