Convert camelCaseText to Sentence Case Text

后端 未结 20 2164
闹比i
闹比i 2020-11-28 03:44

How can I convert a string either like \'helloThere\' or \'HelloThere\' to \'Hello There\' in JavaScript?

20条回答
  •  一整个雨季
    2020-11-28 04:24

    One more solution based on RegEx.

    respace(str) {
      const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g;
      return str.replace(regex, '$& ');
    }
    

    Explanation

    The above RegEx consist of two similar parts separated by OR operator. The first half:

    1. ([A-Z]) - matches uppercase letters...
    2. (?=[A-Z][a-z]) - followed by a sequence of uppercase and lowercase letters.

    When applied to sequence FOo, this effectively matches its F letter.

    Or the second scenario:

    1. ([a-z]) - matches lowercase letters...
    2. (?=[A-Z]) - followed by an uppercase letter.

    When applied to sequence barFoo, this effectively matches its r letter.

    When all replace candidates were found, the last thing to do is to replace them with the same letter but with an additional space character. For this we can use '$& ' as a replacement, and it will resolve to a matched substring followed by a space character.

    Example

    const regex = /([A-Z])(?=[A-Z][a-z])|([a-z])(?=[A-Z])/g
    const testWords = ['ACoolExample', 'fooBar', 'INAndOUT', 'QWERTY', 'fooBBar']
    
    testWords.map(w => w.replace(regex, '$& '))
    ->(5) ["A Cool Example", "foo Bar", "IN And OUT", "QWERTY", "foo B Bar"]
    

提交回复
热议问题