Putting space in camel case string using regular expression

If the first character is always lowercase.

'camelCaseString'.replace(/([A-Z]+)/g, ' $1')

If the first character is uppercase.

'CamelCaseString'.replace(/([A-Z]+)/g, ' $1').replace(/^ /, '')

var rex = /([A-Z])([A-Z])([a-z])|([a-z])([A-Z])/g;

"CSVFilesAreCoolButTXT".replace( rex, '$1$4 $2$3$5' );
// "CSV Files Are Cool But TXT"

And also

"CSVFilesAreCoolButTXTRules".replace( rex, '$1$4 $2$3$5' );    
// "CSV Files Are Cool But TXT Rules"

The text of the subject string that matches the regex pattern will be replaced by the replacement string '$1$4 $2$3$5', where the $1, $2 etc. refer to the substrings matched by the pattern's capture groups ().

$1 refers to the substring matched by the first ([A-Z]) sub-pattern, and $3 refers to the substring matched by the first ([a-z]) sub-pattern etc.

Because of the alternation character |, to make a match the regex will have to match either the ([A-Z])([A-Z])([a-z]) sub-pattern or the ([a-z])([A-Z]) sub-pattern, so if a match is made several of the capture groups will remain unmatched. These capture groups can be referenced in the replacement string but they have have no effect upon it - effectively, they will reference an empty string.

The space in the replacement string ensures a space is inserted in the subject string every time a match is made (the trailing g flag means the regular expression engine will look for more than one match).

Tags:

Regex