Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have literal strings?

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?

like image 209
DevelopingChris Avatar asked Mar 31 '10 14:03

DevelopingChris


People also ask

What are JavaScript literals?

Literals represent values in JavaScript. These are fixed values—not variables—that you literally provide in your script.

How do you write literals in JavaScript?

A string literals are either enclosed in the single quotation or double quotation as ( ' ) and ( “ ) respectively and to concatenate two or more string we can use + operator. Examples for string are “hello”, “hello world”, “123”, “hello” + “world” etc.

Can a string be a literal?

A string literal or anonymous string is a string value in the source code of a computer program. In modern programming languages usually use a quoted sequence of characters, formally "bracketed delimiters", as in x = "foo" . Where "foo" is a string literal with value foo .

How many types of literals are in JavaScript?

We'll cover four types of literals - string literals, number literals, boolean literals and null literals.


2 Answers

Short answer: No

Long answer: Noooooooooooooooooooooooooo

like image 192
Peter Bailey Avatar answered Sep 22 '22 05:09

Peter Bailey


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/

like image 22
Pointy Avatar answered Sep 18 '22 05:09

Pointy