Insert space before capital letters

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

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

提交回复
热议问题