Add a space between two words

javascript

Solution

You can use a regex to add a space wherever there is a lowercase letter next to an uppercase one.

Something like this:

"LightPurple".replace(/([a-z])([A-Z])/, '$1 $2')

UPDATE: If you have more than 2 words, then you'll need to use the `g` flag, to match them all.

"LightPurpleCar".replace(/([a-z])([A-Z])/g, '$1 $2')

UPDATE 2: If are trying to split words like `CSVFile`, then you might need to use this regex instead:

"CSVFilesAreCool".replace(/([a-zA-Z])([A-Z])([a-z])/g, '$1 $2$3')

Problem

I have some words like "Light Purple" and "Dark Red" which are stored as "LightPurple" and "DarkRed". How do I check for the uppercase letters in the word like "LightPurple" and put a space in between the words "Light" and "Purple" to form the word "Light Purple". thanks in advance for the help

Original source

Related problems