Insert space before capital letters

前端 未结 8 1179
误落风尘
误落风尘 2020-12-02 07:01

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

How can I do this in jQuery or JavaScript?

相关标签:
8条回答
  • 2020-12-02 07:55

    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()
    
    0 讨论(0)
  • 2020-12-02 07:56

    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)

    0 讨论(0)
提交回复
热议问题