Frank
Frank

Reputation: 509

Space between lowercase and uppercase letters in a string in JavaScript

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

Answers (4)

Jon Egerton
Jon Egerton

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

T.J. Crowder
T.J. Crowder

Reputation: 1074595

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

Upvotes: 2

Arnaud F.
Arnaud F.

Reputation: 8452

something simple like that :

"LoL".replace(/([a-z])([A-Z])/g, "$1 $2")

is maybe sufficient ;)

Upvotes: 4

user113716
user113716

Reputation: 322502

var str = "FruityLoops";

str = str.replace(/([a-z])([A-Z])/g, '$1 $2');

Example: http://jsfiddle.net/3LYA8/

Upvotes: 22

Related Questions