Add a space between two words

I have words like “Light Purple” and “Dark Red” which are stored as “LightPurple” and “DarkRed”. How to check the capital letters in the word "LightPurple" and put a space between the words "Light" and "Purple" to form the word "Light Purple".

in advance for help

+4
javascript
source share
3 answers

You can use regex to add a space where there is a lowercase letter next to uppercase.

Something like that:

"LightPurple".replace(/([az])([AZ])/, '$1 $2') 

UPDATE If you have more than two words, you need to use the g flag to match all of these.

 "LightPurpleCar".replace(/([az])([AZ])/g, '$1 $2') 

UPDATE 2 . If you are trying to separate words like CSVFile , you may need to use this regular expression instead:

 "CSVFilesAreCool".replace(/([a-zA-Z])([AZ])([az])/g, '$1 $2$3') 
+11
source share

Ok, share your experience. I have this execution in some other languages, and it works great. For you, I just created a javascript version with an example so that you try to do 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 a demon.

+1
source share

You can compare each character with a string of capital 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.

0
source share

All Articles