How to Insert Space After Every 4th Character in Input in Javascript

In this tutorial, you will learn how to insert space after every 4th character in input with javascript. A string is a collection of letters and numbers that can include words, punctuation, and other symbols. Spaces are frequently used to divide the characters in a string, which makes the string’s meaning obvious and simple to understand. A string can be one character long or many words and characters long. For a newbie developer, it can be a bit tricky to insert space after every 4th character in input.

There are numerous ways to insert space after every 4th character in input. We are going to use the simplest approach which involves the usage of the regex pattern as well as replace() method. The replace() method searches the string for a particular value or a regex pattern and it returns a new string with the replaced values.

In the following example, we have an input element and upon click of a button, we will insert space after every 4th character in the input with a dash. Please have a look over the code example and the steps given below.

HTML & CSS

  • We have 3 elements in the HTML file (div, h1, and input).
  • The div element is just a wrapper for the rest of the elements. We are using style attribute with div element to center align the child elements.
  • We have also included our javascript file script.js with a script tag at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
      
    <div style="text-align: center">
        <input type="text" placeholder="Enter Text">    
      <button>Update</button>
    </div>
    <script src="script.js"></script>
</body>
</html>

Javascript

  • We have selected the input element and button element using document.querySelector() method and stored them in the input and btn variables respectively.
  • The regex pattern to match every 4th character in a string is stored in regex variable.
  • We have attached a click event listener to the button element.
  • In the event handler function, we are taking value of the input element and calling replace() method with  regex pattern. As a result, it will return a completely new string which has space after every 4th character. We are storing the newValue and updating the value of the input element.
let input = document.querySelector("input");
let btn = document.querySelector("button");

let regex = /(.{4})/g;
btn.addEventListener("click", (e) => {
 let newValue = input.value.replace(regex, "$1 ");
  input.value = newValue
});