Space between uppercase and lowercase letters in a string in JavaScript

I want to add a space between lowercase and uppercase letters on the same line. For example:

FruityLoops FirstRepeat 

Now I want to add a space between lowercase and uppercase letters. I do not know how to start with JavaScript. Something with substr or search? Can someone help me?

+6
javascript uppercase lowercase
source share
4 answers
 var str = "FruityLoops"; str = str.replace(/([az])([AZ])/g, '$1 $2'); 

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

+18
source share

something simple:

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

perhaps enough;)

+3
source share

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")); // "Fruit Loops" 

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

+2
source share

The regexp option looks better. The correct regexp expression usually looks complex.

Here is another question with more complex parameters:

Regular expression, split the string with an uppercase letter, but ignore the TLA

0
source share

All Articles