Insert space before capital letters
You can just add a space before every uppercase character and trim off the leading and trailing spaces
s = s.replace(/([A-Z])/g, ' $1').trim()
This will find each occurrence of a lower case character followed by an upper case character, and insert a space between them:
s = s.replace(/([a-z])([A-Z])/g, '$1 $2');
For special cases when 2 consecutive capital letters occur (Eg: ThisIsATest) add additional code below:
s = s.replace(/([A-Z])([A-Z])/g, '$1 $2');
Might I suggest a slight edit to the currently accepted answer:
function insertSpaces(string) { string = string.replace(/([a-z])([A-Z])/g, '$1 $2'); string = string.replace(/([A-Z])([A-Z][a-z])/g, '$1 $2') return string;}
This means that:
ACROText -> ACRO TextUserNameTest -> User Name Test
Which might be slightly more useful if you are dealing with db column names (And are using acronyms for some things)