Categories
JavaScript Answers

How to Insert a Space Before Each Capital Letter with JavaScript?

Spread the love

To insert a space before each capital letter with JavaScript, we can use a regex to grab each capital letter and add a space before each one with the replace method

For instance, we can write:

const str = "MySites"
const newStr = str.replace(/([A-Z])/g, ' $1').trim()
console.log(newStr)

We call replace on the string str with /([A-Z])/g to get all capital letters from the string.

The g flag matches all capital letters.

Then we pass in ' $1' as the second argument to add a space before each match.

Finally, we call trim to trim off any leading and trailing whitespaces.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *