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 \"Lig
You could compare each character to a string of uppercase letters.
function splitAtUpperCase(input){
var uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
//start at 1 because 0 is always uppercase
for (var i=1; i<input.length; i++){
if (uppers.indexOf(input.charAt(i)) != -1){
//the uppercase letter is at i
return [input.substring(0,i),input.substring(i,input.length)];
}
}
}
The output is an array with the first and second words.
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.