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: 2020-06-23T12:07:53+05:30

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements