Backslash in Regular Expressions

JavaScript FAQ | JavaScript Strings and RegExp FAQ  

Question: How do I match a backslash using regular expressions?

Answer: The following regular expressions will allow you to match or replace backslashes:

/\\/    // (1) matches one backslash (the 1st occurrence only)
/\\/g   // (2) matches any occurrence of backslash (global search)
re1 = new RegExp("\\\\","")   // same as (1), with RegExp constructor
re2 = new RegExp("\\\\","g")  // same as (2), with RegExp constructor
Note that, to match a backslash verbatim, in accordance with JavaScript regular expression syntax you need two backslash characters in your regular expression literals such as /\\/ or /\\/g. When calling a RegExp constructor, you have to double each of the two backslashes in the string argument passed to the constructor, like this: "\\\\".

Here are some more examples:

// Test if str contains at least one backslash
strHasBackslashes = (/\\/).test(str);

// Replace any '\' in str1 with '/' and store the result in str2
str2 = str1.replace(/\\/g,"/");
Below are the same examples rewritten with RegExp constructor calls:
// Test if str contains at least one backslash
re1 = new RegExp("\\\\","")
strHasBackslashes = re1.test(str);

// Replace any '\' in str1 with '/' and store the result in str2
re2 = new RegExp("\\\\","g"); 
str2 = str1.replace(re2,"/");

Copyright © 1999-2011, JavaScripter.net.