How to create JavaScript regexes using string variables?


Yes, use new RegExp(pattern, flags) to achieve this in JavaScript.You can try to run the following code to implement JavaScript regex using string variables −

<!DOCTYPE html>
<html>
   <body>
      <script>
         var str = 'HelloWorld'.replace( new RegExp('hello', 'i'), '' );
         document.write(str);
      </script>
   </body>
</html>

Updated on: 23-Jun-2020

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements