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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With