Insert a Space before Capital Letters in a String in JS


Borislav Hadzhiev

Thu Nov 18 20212 min read

Insert a Space before Capital Letters in a String #

Use the replace() method to insert a space before the capital letters in a string, e.g. str.replace(/[A-Z]/g, ' $&').trim(). The replace method will return a new string, where each capital letter is replaced by a space preceding the capital letter.

const str = 'AppleBananaKiwi'; const result = str.replace(/[A-Z]/g, ' $&').trim(); console.log(result); // 👉️ "Apple Banana Kiwi"

We passed the following 2 parameters to the String.replace method:

  • a regular expression to match in the string
  • the replacement for each match

The forward slashes / / mark the beginning and end of the regular expression.

The square brackets [] are called a character class and match any uppercase, latin letter from A to Z.

The [A-Z] part is basically an uppercase letter range.

We used the g (global) flag, because we want to match each occurrence of an uppercase letter, and not just the first one.

If you ever need help reading a regular expression, check out this regex cheatsheet from MDN. It's by far the best one out there.

The second parameter we provided to the replace method is the replacement for each match.

The method allows us to specify special replacement strings as parameters.

The $& string inserts the matched substring. In other words it inserts the uppercase letter that we matched.

We have preceded the special string with a space, because we want to insert a space before each capital letter.

In it's entirety, the regular expression matches each capital letter in the string and replaces it with a space and then the capital letter.

The last step is to use the String.trim method to remove any leading or trailing spaces from the new string.

The replace method does not change the original string, it returns a new string. Strings are immutable in JavaScript.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee