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.