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
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')
Okay, sharing my experience. I have this implement in some other languages too it works superb. For you I just created a javascript version with an example so you try this:
var camelCase = "LightPurple";
var tmp = camelCase[0];
for (i = 1; i < camelCase.length; i++)
{
var hasNextCap = false;
var hasPrevCap = false;
var charValue = camelCase.charCodeAt(i);
if (charValue > 64 && charValue < 91)
{
if (camelCase.length > i + 1)
{
var next_charValue = camelCase.charCodeAt(i + 1);
if (next_charValue > 64 && next_charValue < 91)
hasNextCap = true;
}
if (i - 1 > -1)
{
var prev_charValue = camelCase.charCodeAt(i - 1);
if (prev_charValue > 64 && prev_charValue < 91)
hasPrevCap = true;
}
if (i < camelCase.length-1 &&
(!(hasNextCap && hasPrevCap || hasPrevCap)
|| (hasPrevCap && !hasNextCap)))
tmp += " ";
}
tmp += camelCase[i];
}
Here is the demo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With