Reputation: 509
I want to add a space between a lowercase and uppercase in one string. For example:
FruityLoops
FirstRepeat
Now I want to add a space between the lowercase and uppercase letters. I don't know how I should start in JavaScript. Something with substr or search? Can somebody can help me?
Upvotes: 7
Views: 9822
Reputation: 41559
The regexp option looks the best. Getting the regexp right appears to be tricky though.
There's another question here with some more complex options to try:
Regular expression, split string by capital letter but ignore TLA
Upvotes: 0
Reputation: 1074595
You can do it with a manual search, but it may be easier with a regex. Assuming:
Then:
function spacey(str) {
return str.substring(0, 1) +
str.substring(1).replace(/[A-Z]/g, function(ch) {
return " " + ch;
});
}
alert(spacey("FruitLoops")); // "Fruit Loops"
More efficient version inspired by (but different from) patrick's answer:
function spacey(str) {
return str.substring(0, 1) +
str.substring(1).replace(/([a-z])?([A-Z])/g, "$1 $2");
}
alert(spacey("FruityLoops")); // "Fruity Loops"
alert(spacey("FruityXLoops")); // "Fruity X Loops"
Upvotes: 2
Reputation: 8452
something simple like that :
"LoL".replace(/([a-z])([A-Z])/g, "$1 $2")
is maybe sufficient ;)
Upvotes: 4
Reputation: 322502
var str = "FruityLoops";
str = str.replace(/([a-z])([A-Z])/g, '$1 $2');
Example: http://jsfiddle.net/3LYA8/
Upvotes: 22