How to Insert Dash After Every Character in Input in Javascript

In this tutorial, you will learn how to insert dash after every character in input in javascript. An independent clause is usually followed by a dash in an English sentence. A dash has a longer horizontal bar than a hyphen. For a newbie developer, it can be a bit tricky to insert dash after every character in input.

There are numerous ways to insert dash after every 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 dash after every 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 one character at a time 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 dash after every 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 = /(.{1})/g;
btn.addEventListener("click", (e) => {
 let newValue = input.value.replace(regex, "$1—");
  input.value = newValue
});