0

I have the following javascript function with one argument

<script type="text/javascript">
function highlight(text) {
  var inputText = document.getElementById("inputText");
  var innerHTML = inputText.innerHTML;
  var index = innerHTML.indexOf(text);
  if (index >= 0) {
    innerHTML = innerHTML.replace(/YYYYYYYYY/gi, '<span class="highlight">' + text + '</span>');
   inputText.innerHTML = innerHTML;
  }
}
</script>

How can i put function argument text inside this regex rather than YYYYYYYYY

innerHTML = innerHTML.replace(/YYYYYYYYY/gi, '<span class="highlight">' + text + '</span>');
Reham Fahmy
  • 4,803
  • 15
  • 48
  • 70

1 Answers1

2

Use the regex constructor:

re = new RegExp (text, "gi")
Toto
  • 86,179
  • 61
  • 85
  • 118
  • 1
    Thank you and it works perfect `var re = new RegExp (text, "gi");` and then `innerHTML = innerHTML.replace(re, '$&');` – Reham Fahmy Dec 23 '19 at 12:50