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,937
  • 15
  • 50
  • 71

1 Answers1

2

Use the regex constructor:

re = new RegExp (text, "gi")
Toto
  • 89,455
  • 62
  • 89
  • 125
  • 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