Add Space Between Characters in JavaScript
In this tutorial, we are going to learn about how to add a space between characters of a string in JavaScript with the help of examples.
Consider, we have an string with 5 characters:
const user = "John";
Now we need to space between 5 characters for the above string.
To add a space between the characters of a string, we can use the combination of built-in split() and join() methods in JavaScript.
The split() method splits the string into a array of individual characters.
The join() method joins the array of individual characters into a string by adding the space separator between the each character.
Here is an example:
const user = "John";
const result = user.split().join(" ");
console.log(result);
Output:
"J o h n"
In the code above, on the first line we declared a user string with value “John”, after that we called a split().join(” ”) methods on user string by passing a space separator as an argument to the join() method, so that it adds space between each character.
We can also add other separators to the characters like ’/ or -’ in the place of space.
Here is an example:
const user = "John";
const result = user.split().join("-");
console.log(result);
Output:
"J-o-h-n"