13

I was trying to make a pipe in typescript that would split a PascalCase string, but it would be nice if this would also split on digits as well. I would also like it to split on consecutive capital letters. I have this pipe, which works great, except it only works in Chrome and not Firefox, evidently only Chrome supports look backs. How can accomplish this without look backs?

transform(value: string): string {
        let extracted = '';
        if (!value) {
            return extracted;
        }

        const regExSplit = value
            .split(new RegExp('(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[0-9])(?=[A-Z][a-z])|(?<=[a-zA-Z])(?=[0-9])'));
        for (let i = 0; i < regExSplit.length; i++) {
            if (i !== regExSplit.length - 1) {
                extracted += `${regExSplit[i]} `;
            } else {
                extracted += regExSplit[i];
            }
        }

        return extracted;
    }

So for example a string ANet15Amount should be transformed into A Net 15 Amount. This regex above also would split a camelCase string, but that's not necessary to consider.

2
  • .replace(/([A-Z]|\d+)/g, " $1").trim(); Nov 14, 2019 at 16:32
  • 2
    @ibrahimmahrir (?!^)([A-Z]|\d+) avoids first space and doesn't need trim.
    – ctwheels
    Nov 14, 2019 at 16:35

4 Answers 4

12

How about matching by a more basic pattern like this and joining with space.

let str = `ANet15Amount`;

let camel = str.match(/[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+/g).join(' ');

console.log(camel);

First I thought of simply [A-Z][a-z]*|\d+ but this would break eg ABCDefg123 into A B C Defg 123 which would be different working to your current function, that transforms to ABC Defg 123.

There is still a little difference. Yours transforms A1B2 to A 1B 2 and this one to A 1 B 2 where I think this one would be more accurate, wouldn't it.

2
  • 1
    Brilliant, passed all my test cases. I agree, yours is more accurate. I really appreciate it!
    – pearcebdev
    Nov 14, 2019 at 17:45
  • @develmatik Glad it works as desired, I just read about the differences of Camel to PascalCase :) Nov 14, 2019 at 17:51
6

Just replace any uppercase letter [A-Z] or any sequence of digits \d+ with a space plus what we just matched " $1". We skip the first letter so that no space will be added at the begining of the resulting string by adding a negative lookahead on the start of the string (?!^):

// ...

return value.replace(/(?!^)([A-Z]|\d+)/g, " $1");

Example:

let value = "ANet15Amount";

let result = value.replace(/(?!^)([A-Z]|\d+)/g, " $1");

console.log(result);

2

Try [A-Z]?[a-z]+|[A-Z]|[0-9]+

  • 0 or 1 uppercase letter directly followed by 1 or more lowercase letters
  • or 1 uppercase letter
  • or 1 or more digits

Test in generator: https://regex101.com/r/uBO0P5/1

2

I guess it depends on the string's conventions which may increase the complexity

// here 'TIMES' & 'with' are seperated (example 2)
const str = 'SplittingStringsIsFunTimesA100000aaaTIMESwithFollowUp';

// here 'TIMES' & 'With' are seperated (exmpaple 3)
const str2 = 'SplittingStringsIsFunTimesA100000aaaTIMESWithCAPITAL5FollowUp';


// 1. USING REGEX - MATCH
console.log(
  '1. USING REGEX:\n',
  str
  .match(/(\d+|[a-z]+|[A-Z][a-z]*)/g)
  .join(' ')
);


// 2. USING REGEX - MATCH (KEEP ALL CAPITAL CHARS)
console.log(
  '2. USING REGEX (GROUP ALL):\n',
  str
  .match(/(\d+|[a-z]+|([A-Z]([A-Z]+|[a-z]*)))/g)
  .join(' ')
);

// 3. USING REGEX - MATCH (KEEP CAPITAL CHARS BUT LAST)
console.log(
  '3. USING REGEX (GROUP BUT LAST):\n',
  str2
  .match(/(\d+|[a-z]+|([A-Z]([a-z]+|([A-Z]+(?![a-z]))?)))/g)
  .join(' ')
);


// 4. USING SPLIT - FILTER
console.log(
  '4. USING SPLIT:\n',
  str2
  .split(/(\d+|[A-Z][a-z]*)/)
  .filter(v => v !== '')
  .join(' ')
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.