Wagm
Wagm

Reputation: 368

Javascript strings with symbol '\'

I am having difficulties handling symbol \ in javascript. Strings seems to ignore it, for example alert('a\b') would only alert a.

My goal is to write following function which would give me latex image:

function getLatexImage(tex)
{
    return 'http://chart.apis.google.com/chart?cht=tx&chl=' + tex;
}

However calling getLatexImage('\frac{a}{b}') gives me: "http://chart.apis.google.com/chart?cht=tx&chl= rac{a}{b}"

\f is being ignored.

Any suggestions?

Upvotes: 1

Views: 3155

Answers (4)

ventaquil
ventaquil

Reputation: 2848

Use \\. Single slashes are used for special signs (like \n, \t..)

Upvotes: 3

Artur Kedzior
Artur Kedzior

Reputation: 4263

You can simply escape it by adding another backslash

 '\\b'

Upvotes: 2

baao
baao

Reputation: 73251

The backslash \ is a escape character in JavaScript and many other programming languages. If you want to output it, you'll need to escape it by itself.

\\a

for example would output \a.

That being said, if you want to use it in an url you should encode it for safety.

%5c

translates to \

Upvotes: 2

Quentin
Quentin

Reputation: 944021

\ is an escape character. It starts an escape sequence.

\n is a new line. \t is a tab. An escape sequence that has no special meaning usually gets turned into the character on the RHS (so \b is b).

To have a backslash as data in a string literal you have to escape it:

alert('a\\b'); 

Upvotes: 4

Related Questions