145

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

How can I do this in jQuery or JavaScript?

Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44
CLiown
  • 13,665
  • 48
  • 124
  • 205
  • 1
    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? – Pointy Apr 07 '11 at 13:54
  • 2
    Please be more precise, I don't think anyone can understand what you're asking – Clement Herreman Apr 07 '11 at 13:55
  • 1
    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.... – JohnSmith Apr 07 '11 at 13:59
  • "between MySites". How can you place a space between 1 thing? I assume you want "My Sites" as an output. – gen_Eric Apr 07 '11 at 14:06
  • #meagar -- nice comment(sarcasm). weren't you ever taught that if you have nothing nice to say, don't say anything at all? – carinlynchin Jul 16 '15 at 13:54

9 Answers9

260

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()
user2051552
  • 2,870
  • 1
  • 14
  • 7
148

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');
abe312
  • 2,547
  • 25
  • 16
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • 4
    Just a warning, this fails for single letters "ThisIsATest" will result "This Is ATest". – Ceres Apr 28 '14 at 14:37
  • 4
    @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"`. – Guffa Apr 28 '14 at 14:59
  • 1
    for the "ThisIsATest" --(not counting the 'RunThisSQLQuery') you could do this: str.replace(/([A-Z])/g, ' $1').trim() – carinlynchin Jul 16 '15 at 14:01
  • Brilliant! Thanks! – Ami Schreiber Mar 23 '17 at 18:46
37

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)

JosephGarrone
  • 4,081
  • 3
  • 38
  • 61
  • 4
    This works perfectly for what I was needing. It perfectly added a space between capital letters but kept acronyms together. – mighty_mite Sep 14 '16 at 16:56
10

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"
Thomas Stein
  • 671
  • 1
  • 7
  • 11
7

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(); })
Community
  • 1
  • 1
Devin Burke
  • 13,642
  • 12
  • 55
  • 82
5

regex to find lower case - upper case boundary then insert a space

<div id='x'>ThisIsMySites</div>
$('#x').text( $('#x').text().replace(/([a-z])([A-Z])/g, "$1 $2") );

http://jsfiddle.net/uXy64/

Adam Straughan
  • 2,766
  • 3
  • 20
  • 27
4

In a single regex replace (without trims or joins) that allows any character not just letters [a-z] or [A-Z].

const str = "MySites";
str.replace(/(?<!^)([A-Z])/g, " $1"); // -> "My Sites"

You can check more about the look behind (?<!^) here.

Edit:

Added the global /g flag to be able to do multiple replacements.

Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
4

This is another possibility, way much compact

export function replaceCamelSpaces(colorName){
   return colorName.replace(/\B([A-Z])\B/g, ' $1');
}

Explained :

\B uppercase word boundary to find, for more read this

([A-Z]) finding zero, one or more occurence of Upper letters

\B as before but at the end of the search

/g match all occurences of previous matches

replace with

' $1'

Replace with some letter(lowacase) and a space at beginning

Carmine Tambascia
  • 1,628
  • 2
  • 18
  • 32
3

You can use String#split() and a look-ahead for the capitalized alphabet ([A-Z]) and then Array#join() the array with a space:

let stringCamelCase = "MySites";

let string = stringCamelCase.split(/(?=[A-Z])/).join(" ");

console.log(string)

Or, as a String Object function:

String.prototype.cC2SC = function() {
  return this.split(/(?=[A-Z])/).join(" ");
}

console.log("MyCamelCase".cC2SC());
Luca Kiebel
  • 9,790
  • 7
  • 29
  • 44