JavaScript regex to split camel case string

Viewed 203

I have been trying to split a string with space when camel case happens. This is so far I can:

CamelCaseSplit = (inputString) => {
    const f = str => str.match(/^[A-Z]?[^A-Z]*|[A-Z][^A-Z]*/g).join(' 
 <CAMEL> ');
    return f(inputString);
}

It can handle string likes "camelCase", "simple", "number1Case2".

But fails for "ABCWordDEF" and gives me "A B C Word D E F" instead of "ABC Word DEF".

Also the output of "abcDeF123" should be "abc De F123"

How to properly implement splitting into camel case?

2 Answers

You can use

(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])

To replace with a space. See the regex demo. Details:

  • (?<=[a-z\d])(?=[A-Z]) - a location between a lowercase letter or a digit, and a an uppercase letter
  • | - or
  • (?<=[A-Z])(?=[A-Z][a-z]) - a location between an uppercase letter and a sequence of an uppercase letter + a lowercase letter.

See the JavaScript demo:

CamelCaseSplit = (inputString) => {
    const f = str => str.replace(/(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g, ' ');
    return f(inputString);
}
const texts = ['camelCase','simple','number1Case2','ABCWordDEF','abcDeF123'];
for (const s of texts) {
  console.log(s, '->', CamelCaseSplit(s))
}

Related