0

I was just doing stuff in microsoft edge console, and I noticed that when I type in the following:

str = "<script>"

it returns with the value of the string as:

'<\script>'

Why did it add a backslash?

user16791137
  • 111
  • 6
  • If you `console.log(str)` after declaring it, it will log the expected, unescaped string (and then `undefined`, the result of evaluating `console.log`) – pilchard Dec 15 '21 at 21:59

1 Answers1

0

It's formatting it the way you should do it if you were writing the string in a <script> block of an HTML file. In these blocks you should not write <script> and </script> literally, because they'll be parsed as starting or ending the block. The escaped character prevents them from being recognized as those HTML tags.

This is somewhat related to Why split the <script> tag when writing it with document.write()?

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I don't think that is the correct answer. If this would be the reason then it would apply to all strings that are formatted as HTML, but it doesn't. He is simply assigning a string value to a variable in JavaScript, not rendering any HTML. Also, neither Safari, Firefox nor the NodeJS runtime displays it like that. It is only in Chrome and Edge (which is Chromium based). Furthermore, in the Chrome console when you execute `' –  Dec 15 '21 at 22:18
  • No, `` need special treatment. Actually, only `` does, but it looks like Edge is being extra cautious. – Barmar Dec 15 '21 at 22:19