Insert space before capital letters

2019-01-13 02:32发布

问题:

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

How can I do this in jQuery or JavaScript?

回答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()


回答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');


回答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)



回答4:

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(); })


回答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/



回答6:

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());