How to make this positive lookbehind regular expression run in Safari

Viewed 206
(?<=a)(?=b)|(?<=b)(?=a)

I use this regex to insert a "|" between every pair of 'ab' or 'ba', for example:

ab -> a|b
aba -> a|b|a
ababa -> a|b|a|b|a
aaabbbaaabaaaaaab -> aaa|bbb|aaa|b|aaaaaa|b

but it doesn't work in Safari, because it doesn't support positive lookbehind.

Is there an alternative way to change this regular expression so it can work in Safari?

2 Answers

You may use

.replace(/(a)(?=b)|(b)(?=a)/g, '$1$2|')

See the regex demo online.

Details

  • (a)(?=b) - matches and captures a into Group 1 if there is b immediately on the right
  • | - or
  • (b)(?=a) - matches and captures b into Group 2 if there is a immediately to the right of the current location.

The replacement is Group 1 + Group 2 vaues (only one of them will be populated with text upon a match) and a | char.

See the JS demo below:

var rx = /(a)(?=b)|(b)(?=a)/g;
var strs = ['aba', 'abab', 'aaabbbababab'];
for (var s of strs) {
   console.log(s, '=>', s.replace(rx, '$1$2|'));
}

Lookarounds are not needed here. We can just do two separate greedy replacements for ab and ba:

var input = "aaabbbaaabaaaaaab";
var output = input.replace(/ab/g, "a|b").replace(/ba/g, "b|a");
console.log(output);

Related