Categories
JavaScript Answers

How to insert space before capital letters with JavaScript?

Spread the love

Sometimes, we want to insert space before capital letters with JavaScript.

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

How to insert space before capital letters with JavaScript?

To insert space before capital letters with JavaScript, we can use the string replace method.

For instance, we write

const newS = s.replace(/([A-Z])/g, " $1").trim();

to call s.replace with the /([A-Z])/g to match all capital letters in string s.

The 2nd argument is ' $1' which means we add a space before the matched substring.

Finally, we call trim to trim the starting and ending whitespaces from the returned string.

Conclusion

To insert space before capital letters with JavaScript, we can use the string replace method.

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 *