JSFiddle - React, Tailwind, and code Playground
HTML
<pre id="output"></pre>
JavaScript
$('#output').append('foobar'.replace(/(?=(bar))/g, '[$1]') + "\n");
$('#output').append('foobar'.replace(/(?=(bar))?/g, '[$1]') + "\n");
$('#output').append('foobar'.replace(/(?:(?=(bar)))?/g, '[$1]') + "\n");