Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Crockford - Chapter 8 - page 86

Crockford: "JavaScript: The Good Parts"

Chapter 8: Methods

RegExp regexp.exec(string)

At the very end of page 86 there is a nice example but I don't yet understand one small thing in it.

var text = '<html><body bgcolor=linen><p>' +
'This is <b>bold<\/b>!<\/p><\/body><\/html>';

Why are the / (forward slashes) escaped here?

I tried the example without them, seems to work just fine.

like image 896
peter.petrov Avatar asked Dec 09 '25 23:12

peter.petrov


1 Answers

In a JavaScript string, there is no difference between / and \/.

Inside a <script> element the sequence </script> will end the element. To represent it inside a string as data, you can use <\/script>.

When generating JavaScript strings programatically, it is a common practise to escape all / characters as a defence against terminating scripts when used inside HTML.

This is just code that follows that pattern. There is no actual benefit achieved with this particular code.

like image 141
Quentin Avatar answered Dec 12 '25 13:12

Quentin