JavaScript - How to Add Spaces Between Words Starting with Capital Letters Using RegExp?
Here are the different ways to add spaces between words starting with capital letters using RegExp in JavaScript
1. Use Regex with the replace Method
This is the most direct and widely used approach.
let s = "HelloWorldThisIsRegex";
s = s.replace(/([A-Z])/g, " $1").trim();
console.log(s);
Output
Hello World This Is Regex
- /([A-Z])/: Matches each capital letter individually.
- (...): Captures the matched capital letter.
- $1: Refers to the captured group in the replacement string.
- " $1": Adds a space before the matched letter.
- .replace(): Applies the regex replacement to the string.
- .trim(): Removes the leading space caused by adding a space before the first capital letter.
2. Split String and Rejoin
Split the string at capital letters and rejoin with spaces.
let s = "HelloWorldThisIsRegex";
let a = s.split(/(?=[A-Z])/).join(" ");
console.log(s);
Output
HelloWorldThisIsRegex
- /(?=[A-Z])/: Matches a position (?= is a "lookahead") before any capital letter.
- .split(): Splits the string wherever the regex matches.
- .join(" "): Combines the resulting array into a single string, with spaces between the elements.
3. Use a Loop with Regex Matching
Iteratively add spaces while traversing the string.
let s = "HelloWorldThisIsRegex";
let res = "";
for (let n = 0; n < s.length; n++) {
res += /[A-Z]/.test(s[n]) && n !== 0 ? " " + s[n] : s[n];
}
console.log(res);
Output
Hello World This Is Regex
- /[A-Z]/.test(s[n]): Checks if the current character is a capital letter.
- n !== 0: Ensures no space is added before the first character.
- result += ...: Builds the resulting string by appending either the character or the character with a space.
4. Manually Build the Regex Replacement
If you want to avoid using the replace function, use a regex match and construct the result.
let s = "HelloWorldThisIsRegex";
let a = s.match(/[A-Z][a-z]*/g);
let res = a.join(" ");
console.log(res);
Output
Hello World This Is Regex
- /[A-Z][a-z]*/g: Matches a capital letter followed by zero or more lowercase letters, capturing each "word".
- .match(): Returns an array of all matches.
- .join(" "): Combines the words with spaces.