Categories
JavaScript Answers

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

Spread the love

Sometimes, we want to insert a space before each capital letter with JavaScript.

In this article, we’ll look at how to insert a space before each capital letter with JavaScript.

Insert a Space Before Each Capital Letter with JavaScript

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.

Conclusion

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

Leave a Reply

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