We should double for a backslash escape a forward slash /
in a regular expression.
alert( "1\\2".match(/\\/) ); // '\'
A backslash \
is used to denote character classes, e.g. \d
. So it’s a special character in regular expression (just like in regular strings).
A slash symbol '/'
is not a special character, but in JavaScript, it is used to open and close the RegEx: /...pattern.../
, so we should escape it too.
Regex escape forward-slash JavaScript Example
HTML example code.
<!DOCTYPE html>
<html>
<body>
<script>
myString = '/courses/test/user';
myString = myString.replace(/<br\/\>/g,'\n');
console.log(myString);
</script>
</body>
</html>
Output:
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version