Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a space between two words

Tags:

javascript

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

like image 951
kkh Avatar asked Mar 11 '13 16:03

kkh


2 Answers

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')
like image 54
Rocket Hazmat Avatar answered Sep 20 '22 02:09

Rocket Hazmat


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.

like image 20
KMX Avatar answered Sep 19 '22 02:09

KMX