Escaping HTML entities in JavaScript string literals within the [removed] block

前端 未结 5 743

On the one hand if I have

\';
console.log(s);

the browser will terminate the

5条回答
  •  不知归路
    2020-12-03 05:17

    (edit - somehow didn't notice you mentioned slash-escape in your question already...)

    OK so you know how to escape a slash.

    In inline event handlers, you can't use the bounding character inside a literal, so use the other one:

    test

    But this is all in aid of making your life difficult. Just don't use inline event handlers! Or if you absolutely must, then have them call a function defined elsewhere.

    Generally speaking, there are few reasons for your server-side code to be writing javascript. Don't generate scripts from the server - pass data to pre-written scripts instead.

    (original)

    You can escape anything in a JS string literal with a backslash (that is not otherwise a special escape character):

    var s = 'Hello <\/script>';
    

    This also has the positive effect of causing it to not be interpreted as html. So you could do a blanket replace of "/" with "\/" to no ill effect.

    Generally, though, I am concerned that you would have user-submitted data embedded as a string literal in javascript. Are you generating javascript code on the server? Why not just pass data as JSON or an HTML "data" attribute or something instead?

提交回复
热议问题