Insert space before capital letters

93,409

Solution 1

You can just add a space before every uppercase character and trim off the leading and trailing spaces

s = s.replace(/([A-Z])/g, ' $1').trim()

Solution 2

This will find each occurrence of a lower case character followed by an upper case character, and insert a space between them:

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

For special cases when 2 consecutive capital letters occur (Eg: ThisIsATest) add additional code below:

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

Solution 3

Might I suggest a slight edit to the currently accepted answer:

function insertSpaces(string) {
    string = string.replace(/([a-z])([A-Z])/g, '$1 $2');
    string = string.replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
    return string;
}

This means that:

ACROText -> ACRO Text
UserNameTest -> User Name Test

Which might be slightly more useful if you are dealing with db column names (And are using acronyms for some things)

Solution 4

Here is what i ended up using to convert a string to a title case, based on a few of the answers here:

str = str
  .replace(/(_|-)/g, ' ')
  .trim()
  .replace(/\w\S*/g, function(str) {
    return str.charAt(0).toUpperCase() + str.substr(1)
  })   
  .replace(/([a-z])([A-Z])/g, '$1 $2')
  .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')   

Here is a JSFiddle where you can test your string to see if this meets your needs: https://jsfiddle.net/thomastasa/5236dv8t/85/


Examples:

  • "yourStringHere" -> "Your String Here"
  • "AnotherStringHere" -> "Another String Here"
  • "someones_string" -> "Someones String"
  • "Another-String-Here" -> "Another String Here"
  • "myAWESOMEString" -> "My AWESOME String"

Solution 5

This should insert a space between each capital letter that was not preceded by a capital letter.

var myString = "MySites"
var newString = "";
var wasUpper = false;
for (var i = 0; i < myString.length; i++)
{
    if (!wasUpper && myString[i] == myString.toUpperCase()[i])
    {
        newString = newString + " ";
        wasUpper = true;
    }
    else
    {
        wasUpper = false;
    }
    newString = newString + myString[i];
}

newString will have the value you want. Also, if you want to shorten your code using regex, you can use the following code from Javascript camelCase to Regular Form

"thisStringIsGood"
    // insert a space before all caps
    .replace(/([A-Z])/g, ' $1')
    // uppercase the first character
    .replace(/^./, function(str){ return str.toUpperCase(); })
Share:
93,409

Related videos on Youtube

CLiown
Author by

CLiown

#SOreadytohelp

Updated on July 08, 2022

Comments

  • CLiown
    CLiown almost 2 years

    I have a string "MySites". I want to place a space between My and Sites.

    How can I do this in jQuery or JavaScript?

    • Pointy
      Pointy about 13 years
      Can you provide some more detail? What is the general form of the strings you want to separate? If it's only that one string, why not just put the space in manually?
    • Clement Herreman
      Clement Herreman about 13 years
      Please be more precise, I don't think anyone can understand what you're asking
    • JohnSmith
      JohnSmith about 13 years
      define the pattern that it should match, e.g. "a space when it find 'My' in the string" or "add a space before each capital character, unless it is the first character", or....
    • gen_Eric
      gen_Eric about 13 years
      "between MySites". How can you place a space between 1 thing? I assume you want "My Sites" as an output.
    • carinlynchin
      carinlynchin almost 9 years
      #meagar -- nice comment(sarcasm). weren't you ever taught that if you have nothing nice to say, don't say anything at all?
  • Ceres
    Ceres almost 10 years
    Just a warning, this fails for single letters "ThisIsATest" will result "This Is ATest".
  • Guffa
    Guffa almost 10 years
    @Ceres: Good point. That case could be handled by instead inserting a space before any capital that is not the first character, but you still have cases that can't be handled without word recognition, like "RunThisSQLQuery".
  • carinlynchin
    carinlynchin almost 9 years
    for the "ThisIsATest" --(not counting the 'RunThisSQLQuery') you could do this: str.replace(/([A-Z])/g, ' $1').trim()
  • One-One
    One-One over 8 years
    This also works for "1AndAbove". The other solution does not. Thanks!!
  • Toni Michel Caubet
    Toni Michel Caubet almost 8 years
    It "fails" for acronyms, how could we prevent for it to act when 2 or more consecutive caps?
  • mighty_mite
    mighty_mite over 7 years
    This works perfectly for what I was needing. It perfectly added a space between capital letters but kept acronyms together.
  • Ami Schreiber
    Ami Schreiber about 7 years
    Brilliant! Thanks!
  • iFreilicht
    iFreilicht almost 7 years
    @ToniMichelCaubet easy, modify the regex like this: /([A-Z]+)/g. The + will make sure you match as many consecutive capital letters as possible.
  • Kristina Bressler
    Kristina Bressler almost 7 years
    Why is parentheses that you use to surround '[A-Z]' needed in this code?
  • user2051552
    user2051552 over 6 years
    @Kristina The parenthesis say 'I am a variable'. Without the parenthesis, it yields the answer '$1y $1ites' for 'MySites'