Home > Blockchain >  How to enter whitespace only once after 4 characters in a string?
How to enter whitespace only once after 4 characters in a string?

Time:09-20

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()"/>

CodePudding user response:

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" />

CodePudding user response:

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  = " "
  }
})

CodePudding user response:

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()" />

  • Related