Skip to content

JavaScript regex escape | Example code

  • by

Use regular expression inside replace method to escape string in JavaScript.

Escape string for use in JavaScript regex

HTML example code URL escape suing regex in JavaScript replace method.

<!DOCTYPE html>
<html>
<body>

  <script>

    function escapeRegExp(input) {
      const source = typeof input === 'string' || input instanceof String ? input : '';
      return source.replace(/[-[/\]{}()*+?.,\\^$|#\s]/g, '\\$&');
    }

    console.log(escapeRegExp("https://tutorial.eyehunts.com/"));
  </script>
</body>
</html>

Output:

JavaScript regex escape

Another function

<!DOCTYPE html>
<html>
<body>

  <script>

    var escapeRegExp;

    (function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
        "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
        ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
      , regex = RegExp('[' + specials.join('\\') + ']', 'g')
      ;

      escapeRegExp = function (str) {
        return str.replace(regex, "\\$&");
      };

    }());

    console.log(escapeRegExp("/path/to/res?search=this.that")); 
  </script>
</body>
</html>

Do comment if you have any doubts or suggestions on this JS escape topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading