Javascript escaping characters for regular expression use


Javascript example to escapes all reserved characters for regular expressions by preceding them with a backslash. You can use this function to scape your string containing regex reserved characters.

<script type="text/javascript">
function makeString(object) {
      if (object == null) return \'\';
      return String(object);
    };

    function escapeRegExp(str) {
          return makeString(str).replace(/([.*+?^=!:${}()|[]/\\])/g, \'\\$1\');
        };
    
    
    //test function
    alert(escapeRegExp(\'<p>?>%*</p>\'));
        
</script>

See output here

js example