How to create JavaScript regexes using string variables?

JavascriptObject Oriented ProgrammingFront End Technology

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>
raja
Published on 27-Feb-2018 11:07:05
Advertisements