Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript and forward slashes in strings

Tags:

javascript

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.

like image 778
rubixibuc Avatar asked May 24 '11 23:05

rubixibuc


People also ask

How do you escape a forward slash in JavaScript?

We should double for a backslash escape a forward slash / in a regular expression. A backslash \ is used to denote character classes, e.g. \d . So it's a special character in regular expression (just like in regular strings).

Does forward slash need to be escaped in JavaScript?

A slash. A slash symbol '/' is not a special character, but in JavaScript it is used to open and close the regexp: /... pattern.../ , so we should escape it too.

How do you replace all slash in a string JavaScript?

To replace all forward slashes in a string:Call the replace() method, passing it a regular expression that matches all forward slashes as the first parameter and the replacement string as the second. The replace method will return a new string with all forward slashes replaced.


2 Answers

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.

like image 132
Quentin Avatar answered Nov 14 '22 11:11

Quentin


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.

like image 27
rid Avatar answered Nov 14 '22 12:11

rid