You can do this with a manual search, but regex can be easier. Assuming that:
- You know what starts with capital
- You do not need space in front of this capital
- You need space in front of all subsequent capitals
Then:
function spacey(str) { return str.substring(0, 1) + str.substring(1).replace(/[AZ]/g, function(ch) { return " " + ch; }); } alert(spacey("FruitLoops"));
Real time example
A more efficient version, inspired by (but different from) patrick's answer :
function spacey(str) { return str.substring(0, 1) + str.substring(1).replace(/([az])?([AZ])/g, "$1 $2"); } alert(spacey("FruityLoops")); // "Fruity Loops" alert(spacey("FruityXLoops")); // "Fruity X Loops"
Real time example
Tj crowder
source share