Computer >> Computer tutorials >  >> Programming >> Javascript

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>