Insert space before capital letters

前端 未结 8 1182
误落风尘
误落风尘 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:51

    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"

提交回复
热议问题