How can I convert a string either like \'helloThere\' or \'HelloThere\' to \'Hello There\' in JavaScript?
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, '$& ');
}
The above RegEx consist of two similar parts separated by OR operator. The first half:
([A-Z])
- matches uppercase letters...(?=[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:
([a-z])
- matches lowercase letters...(?=[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.
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"]