How can I create a regex from a variable so that it has a capture group that can then be used in a replace()
call?
The below is what I have tried so far without success.
var term = 'test'
var r = new RegExp('('+term+')', "ig");
$('#test').html( $('#test').html().replace(r, '<span class="found">'+$1+'</span>') ); // Uncaught ReferenceError: $1 is not defined
.found{
background-color:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="test">This is a test</div>