12

What is the real reason that we must escape a forward slash in a JavaScript string, and also why must we escape string/no string in XHTML. A lot of tutorials just brush over this issue.

3 Answers 3

15

What is the real reason that we must escape a forward slash in a JavaScript string

In an HTML 4 document, the sequence </ inside an element defined as containing CDATA (such as script) is an end tag and will end the element (with an error if it is not </script>.

As far as JS is concerned / and \/ are identical inside a string. As far as HTML is concerned </ starts an end tag but <\/ does not.

, and also why must we escape string/no string in XHTML.

XHTML doesn't provide a method of specifying that an element intrinsically contains CDATA, so you need to explicitly handle characters which would otherwise have special meaning (<, &, etc). Wrapping the contents of the element with CDATA markers is the easiest way to achieve this.

Sign up to request clarification or add additional context in comments.

4 Comments

So we never have to escape a single forward slash, only a </ ? whether it is XHTML inside a string or outside a string? Thanks :-)
In other words in XHTML when must we escape a forward slash?
In "normal" XHTML (which nobody uses), never. In HTML-compatible XHTML (which everybody who wants IE 8 and lower to be supported uses), the same places as in HTML.
So, @rubixibuc, to recap, and make it clear: "So we never have to escape a single forward slash, only a </ ?". Correct.
3

You don't need to escape / in a JavaScript string, just \, because if you don't, then the string yes\no will inadvertently be transformed into yes<newline>o. Escaping the \ will prevent that.

Also, if you don't escape & in a URL, then whatever comes after it will be considered a new parameter. For example, a=Q&A will mean "the parameter a has the value "Q" and there's also a parameter A" instead of "the parameter a has the value "Q&A"". The correct way of escaping that would be a=Q%26A.

2 Comments

Why would you write yes\no for the prompt?
@Paŭlo, you probably wouldn't, that's the best example of unintended use I could come up with.
0

The slash is needed to prevent browsers, particularly older ones, to erroneously interpret the forward slash as a closing JavaScript marker.

2 Comments

There is nothing erroneous about it.
@Quentin, of course, it's erroneous. While in a string mode, the special for the interpreter characters are just characters...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.