Match all instances of character except the first one, without lookbehind

Tags: , , ,

I’m struggling with this simple regex that is not working correctly in Safari:


It should match each ?, except of the first one.

I know that lookbehind is not working on Safari yet, but I need to find some workaround for it. Any suggestions?


You can use an alternation capture until the first occurrence of the question mark. Use that group again in the replacement to leave it unmodified.

In the second part of the alternation, match a questionmark to be replaced.

const regex = /^([^?]*?)|?/g;
const s = "test ? test ? test ?? test /";
console.log(s.replace(regex, (m, g1) => g1 ? g1 : "[REPLACE]"));

Source: stackoverflow