66

I tried many ways to get a single backslash from an executed (I don't mean an input from html).

I can get special characters as tab, new line and many others then escape them to \\t or \\n or \\(someother character) but I cannot get a single backslash when a non-special character is next to it.

I don't want something like:

str = "\apple";   // I want this, to return:
console.log(str); // \apple

and if I try to get character at 0 then I get a instead of \.

Liam
  • 27,717
  • 28
  • 128
  • 190
Mik
  • 2,884
  • 2
  • 19
  • 10
  • Is your question about strings, or regular expressions? Or regular expressions you're creating via strings (e.g., using `new RegExp(string)`)? – T.J. Crowder Apr 06 '12 at 10:09
  • I tried every ways, either regular expressions or string methods, but it really seems that there is no way to handle **verbatim** or **raw** strings in javascript code. – Mik Apr 16 '12 at 08:34

4 Answers4

87

(See ES2015 update at the end of the answer.)

You've tagged your question both string and regex.

In JavaScript, the backslash has special meaning both in string literals and in regular expressions. If you want an actual backslash in the string or regex, you have to write two: \\.

The following string starts with one backslash, the first one you see in the literal is an escape character starting an escape sequence. The \\ escape sequence tells the parser to put a single backslash in the string:

var str = "\\I have one backslash";

The following regular expression will match a single backslash (not two); again, the first one you see in the literal is an escape character starting an escape sequence. The \\ escape sequence tells the parser to put a single backslash character in the regular expression pattern:

var rex = /\\/;

If you're using a string to create a regular expression (rather than using a regular expression literal as I did above), note that you're dealing with two levels: The string level, and the regular expression level. So to create a regular expression using a string that matches a single backslash, you end up using four:

// Matches *one* backslash
var rex = new RegExp("\\\\");

That's because first, you're writing a string literal, but you want to actually put backslashes in the resulting string, so you do that with \\ for each one backslash you want. But your regex also requires two \\ for every one real backslash you want, and so it needs to see two backslashes in the string. Hence, a total of four. This is one of the reasons I avoid using new RegExp(string) whenver I can; I get confused easily. :-)

ES2015 and ES2018 update

Fast-forward to 2015, and as Dolphin_Wood points out the new ES2015 standard gives us template literals, tag functions, and the String.raw function:

// Yes, this unlikely-looking syntax is actually valid ES2015
let str = String.raw`\apple`;

str ends up having the characters \, a, p, p, l, and e in it. Just be careful there are no ${ in your template literal, since ${ starts a substitution in a template literal. E.g.:

let foo = "bar";
let str = String.raw`\apple${foo}`;

...ends up being \applebar.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • How do you console.log() the variable with backslash if it was assigned already (because it came back like that from the server)? – kev Jan 16 '17 at 03:30
  • @kev: I don't understand the question. – T.J. Crowder Jan 16 '17 at 06:59
  • `$.ajax({}).done(function(data){console.log(data)})` Output: `Object {apple: "apple"}` but server actually sent: `{"apple": "\apple"}`. Does it need to be escaped on the server or is there a pure client side solution? – kev Jan 17 '17 at 00:13
  • 2
    @kev: What the server sent is invalid JSON. JSON (unlike JavaScript) doesn't tolerate undefined escape sequences (`\a`). If that's meant to be a backslash, yes, it must be escaped server-side: `{"apple":"\\apple"}`. (You'd want to even if JSON tolerated invalid escapes, because of `{"nectarine":"\nectarine"}`, where that would be `ectarine` because `\n` is a newline.) – T.J. Crowder Jan 17 '17 at 07:36
  • 1
    It looks like the `\12` kind of restrictions (there were also issues with `\u`, `\x` etc.) went away sometime [after late 2016](https://tc39.github.io/proposal-template-literal-revision/), so in modern browsers the only thing to avoid is `${` – ShreevatsaR Feb 13 '18 at 21:41
  • Seems like plugging directly into the debugger should work, but maybe not: Firefox 82.0.2 (32-bit) 13:54:43.577 str = String.raw`\apple`; 13:54:43.646 "\\apple" chrome Version 86.0.4240.183 (Official Build) (64-bit) str = String.raw`\apple` "\apple" – captain puget Nov 08 '20 at 22:00
  • @captainpuget - Not sure what you mean by "plugging directly into the debugger." Template literals and tagged template functions don't relate to the debugger (any more than anything else does). – T.J. Crowder Nov 09 '20 at 07:31
  • 1
    that `String.raw` was the only solution for my problem, thanks. – Accountant م Feb 05 '21 at 06:24
  • ```String.raw`\`;``` doesn't work, but you can cheat and do ```String.raw`\apple`.replace('apple', '');```, it seems to work – TBG May 03 '23 at 08:51
  • @TBG - Yeah, the backslash escapes the backtick. I think I'd probably use something like ```String.raw`\``.slice(0, -1)```. :-) – T.J. Crowder May 03 '23 at 09:11
23

Try String.raw method:

str = String.raw`\apple` // "\apple"

Reference here: String.raw()

Dolphin_Wood
  • 847
  • 5
  • 19
  • 5
    Just be careful you don't have `${` anywhere in the template literal. :-) – T.J. Crowder Jan 09 '16 at 11:28
  • 4
    And you can't have octal literals in template strings either such as `1\2` so this isn't really an effective general technique for avoiding backslash escaping. – Wyck Aug 25 '16 at 14:56
  • ```String.raw`\`;``` doesn't work, but you can cheat and do ```String.raw`\apple`.replace('apple', '');```, it seems to work – TBG May 03 '23 at 08:50
16

\ is an escape character, when followed by a non-special character it doesn't become a literal \. Instead, you have to double it \\.

console.log("\apple");  //-> "apple" 
console.log("\\apple"); //-> "\apple" 

There is no way to get the original, raw string definition or create a literal string without escape characters.

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • 7
    raw string becomes possible via es6 [String.raw](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw) method – Dolphin_Wood Jun 10 '15 at 06:42
-3

please try the below one it works for me and I'm getting the output with backslash

String sss="dfsdf\\dfds";
System.out.println(sss);
Syscall
  • 19,327
  • 10
  • 37
  • 52