59

In C#, Ruby, and many other languages you can denote a string as to not need escaping. In C# it’s like this

string s = @"\whatever\this\is";

The results are when printed:

\whatever\this\is

Is this supported in any form in JavaScript?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DevelopingChris
  • 39,797
  • 30
  • 87
  • 118
  • 4
    Pedantic clarification: Microsoft calls this a verbatim-string-literal, as opposed to the regular-string-literal. So the latter is also a literal and as far as I know this is not peculiar to Microsoft. http://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx – H2ONaCl May 15 '14 at 08:56

6 Answers6

168

Short answer: No

Long answer: Noooooooooooooooooooooooooo

Mogsdad
  • 44,709
  • 21
  • 151
  • 275
Peter Bailey
  • 105,256
  • 31
  • 182
  • 206
  • 2
    I have reverted the recent edit that completely changed this answer, to claim that template literals can be used as literal strings. For a bunch of reasons: (1) To radically change an answer in this way is misleading, (2) there is already another answer (by Iain Reid below) proposing template literals, (3) as commented on the other answer, template literals are *not* literal strings; for instance you cannot put a string containing `\useless` or `${what is this}` inside one of them. – ShreevatsaR Feb 12 '18 at 20:03
  • 2
    There's absolutely no reason to modify this answer - "it shows up in search engines" isn't justification. – Mogsdad Feb 12 '18 at 20:15
  • Perhaps elaborate in your answer why template literal strings can't be used for this. – Peter Mortensen Aug 22 '21 at 15:17
23

I don't know what you're getting at, but one way to get around the problem of escaping (etc) is use a trick that John Resig seems to like a lot. You include <script> blocks in a page, but give them a "type" like "text/plain" to make sure that the browser doesn't hand them over to Javascript. Then use the text of the script block for whatever you like.

<script id='a_string' type='text/plain'>
  Here is some stuff.
  There might be some \escape sequences in it.
</script>

Then you can grab that with $('#a_string').text() (or with getElementById if you're not using jQuery or something like that).

edit: Here's John Resig's explanation about why dropping stuff into script blocks like that is a good idea:

Quick tip: Embedding scripts in your page that have a unknown content-type (such is the case here - the browser doesn't know how to execute a text/html script) are simply ignored by the browser - and by search engines and screenreaders. It's a perfect cloaking device for sneaking templates into your page. I like to use this technique for quick-and-dirty cases where I just need a little template or two on the page and want something light and fast.

Taken from this page: http://ejohn.org/blog/javascript-micro-templating/

Alex
  • 14,104
  • 11
  • 54
  • 77
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 4
    What is the advantage of this over using some other random DOM element hidden from view with CSS? It seems like it breaks the semantics of the script element. – Syntactic Mar 31 '10 at 14:55
  • I don't know, frankly; I've been trying to figure that out. I first came across it in examples for the new jQuery "template" stuff. I agree that it seems squirrely, and especially so when you consider what jQuery does with script blocks when you dynamically insert content via "html()". Still, it's a thing that people do; I'm not sure what the OP is trying to discover or achieve. – Pointy Mar 31 '10 at 15:03
  • @Syntactic I've updated the answer with a snippet from Resig's blog – Pointy Mar 31 '10 at 16:26
  • 2
    I think that this is better than using, say, hidden
    to accomplish the task, in that you are allowed to use "<" and ">" more carelessly. If the template is just a valid HTML then sure you can use
    to enclose it. If however the template is written in some templating language (handlebars, underscore, etc) which supports conditional expressions (if, try, catch) and loops (for, for in, foreach, map, ...) you can quickly end up with a string blob which does not have balanced opening and closing tags, violates nesting rules, has unfinished attributes etc.
    – qbolec Oct 23 '13 at 06:40
  • @qbolec agreed. When I wrote that comment on my answer, I didn't know as much as I do now :) Also, jQuery doesn't strip script blocks that have an explicit type attribute that's non-JavaScript (like "text/html"). – Pointy Oct 23 '13 at 13:37
9

Literal strings are available through the use of ES6 language features. Node.js v4.x now supports these and around 90% of the other ES6 additions as well.

Template literals (Template strings)

In JavaScript, string literals are known as template strings. And the syntax is pretty straightforward.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Iain J. Reid
  • 978
  • 1
  • 11
  • 23
  • 2
    Literal strings and template strings are not really the same thing. A literal string has no characters with special meaning at all. Template strings treat ${ as a special sequence. – DamienG Jan 11 '17 at 20:10
  • 2
    I think in fact the [`String.raw()` method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/raw) (which is part of Template literals) is the closest you could get to template strings. – Mariano Desanze May 16 '17 at 22:37
  • 1
    Try this: `String.raw\`this is a \useless feature\``: it results in “Uncaught SyntaxError: Invalid Unicode escape sequence”. Compare with say `r'this is a \useless feature'` in Python. So template strings (even with `String.raw`) interpret not only `${` but also `\u` (and other) escape sequences. The question's `\whatever\this\is` happens to work with `String.raw`, but that's only because none of the three words happened to start with `u` or `x` for example. :-) – ShreevatsaR Jul 16 '17 at 02:11
  • What were called "literal strings" are now called "template literals", and they don't satisfy the example in the original question, because when I type `\`\whatever\this\is\`` the result is "whatever hisis" (all backslashes are gone and the t has been turned into a tab). Another nit: JavaScript has always had the concept of "string literals" (meaning strings that are enclosed by quotes in code), but they are not verbatim string literals (or "literal strings" as the heading says). – Marcus Oct 05 '17 at 19:00
  • 1
    BTW in the roughly half a year after I left an earlier comment in July 2017, it looks like something like ``console.log(String.raw`\whatever\this\is\a\useless\xylophone`)`` will work now (starting sometime [after this proposal](https://tc39.github.io/proposal-template-literal-revision/)), so now the only thing that a `String.raw` literal cannot contain (if you don't want it to be treated as special) is `${` – ShreevatsaR Feb 13 '18 at 21:46
4

This will work as long as you don't throw a \x into the string!

var str = String.raw`\whatever\this\is`;

console.log(str);
Jonathan Newton
  • 832
  • 6
  • 18
1

Just escape the escapes

var myCrazyString = "\\yes\\we\\have\\no\\bananas"
plodder
  • 2,304
  • 18
  • 19
  • 9
    The question specifically requested "is this supported in any form in javascript" and was referring to "denot[ing] a string as to not need escaping". Adding more escapes is kind of the opposite as not needing escapes... – MandM Jun 03 '15 at 19:45
1

I've got one solution to this ;)

function literalString(regex) {
    return ('' + regex).slice(1, -1);
};

O.innerHTML = literalString(/\whatever\this\is/);
<pre id=O>

You basically convert a regex to a string and remove the first and last characters.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • 3
    A cute idea, but unfortunately it requires your literal string to be a valid regex. (For example, try forming the literal string `[a-` or `*{2,3}` or `**` by surrounding it with `/` on both sides.) This is even more onerous than simply needing to double backslashes. – ShreevatsaR Sep 07 '17 at 20:47