Bi Jieming
Bi Jieming

Reputation: 11

Workaround for JS Regex lookbehind/lookahead for Safari

I have a regex in JS const camel = const camel = /((?<=[A-Z])(?=[A-Z][a-z]))/g;

It basically tries to find the place before is a upper case char and after is an upper case char with following a lower case char.

Some test cases to verify it works:

Below is the case where I find it hard to have an elegant work around..

'runUnitTESt'.replace(camel, ' ') = 'runUnitTE St'

This regex works in Chrome, but not in safari, since it does not support lookbehind/lookahead regex. Spent some time trying to think about a good workaround, but did not find one. Any insight?

Thanks!

Upvotes: 1

Views: 1885

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

In your pattern you have a capture group around the 2 assertions. What you can do is change the first lookbehind assertion into a match instead and keep the second lookahead assertion.

[A-Z](?=[A-Z][a-z])

Regex demo

Then in the replacement use the full match followed by a space $&

const camel = /[A-Z](?=[A-Z][a-z])/g;
console.log('runUnitTESt'.replace(camel, "$& "));

Upvotes: 1

Related Questions