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.
OutputHello 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.
OutputHelloWorldThisIsRegex
- /(?=[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.
OutputHello 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.