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.