You can do it with a manual search, but it may be easier with a regex. Assuming:
- You know it starts with a capital
- You don't want a space in front of that capital
- You want a space in front of all subsequent capitals
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"
Live example
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"
Live example