JavaScript Basics

JavaScript Advanced

JavaScript Arrays

JavaScript Functions

JavaScript Objects

JavaScript DOM

JavaScript String

Regex add space between characters JavaScript

The regex to add space between characters is /(?=.)/g. This regular expression uses a positive lookahead assertion that selects each character.

You pass this regular expression as the first argument and space as the second argument to the string replace() method.

let str = 'JavaScript';
str = str.replace(/(?=.)/g, ' ');
str = str.trim();
console.log(str);

Output

"J a v a S c r i p t"

Explanation of the code:

1. In regular expression, a dot means any character. When the dot is used with a positive lookahead, it selects each character.

2. The string produced by the replace() method has a space at the beginning, so to remove that space trim() method was called.

Recommended Posts