Escape quotes in JavaScript

前端 未结 13 594
不思量自难忘°
不思量自难忘° 2020-11-22 11:39

I\'m outputting values from a database (it isn\'t really open to public entry, but it is open to entry by a user at the company -- meaning, I\'m not worried about XSS).

相关标签:
13条回答
  • 2020-11-22 11:50

    You need to escape quotes with double backslashes.

    This fails (produced by PHP's json_encode):

    <script>
      var jsonString = '[{"key":"my \"value\" "}]';
      var parsedJson = JSON.parse(jsonString);
    </script>
    

    This works:

    <script>
      var jsonString = '[{"key":"my \\"value\\" "}]';
      var parsedJson = JSON.parse(jsonString);
    </script>
    
    0 讨论(0)
  • 2020-11-22 11:52

    &quot; would work in this particular case, as suggested before me, because of the HTML context.

    However, if you want your JavaScript code to be independently escaped for any context, you could opt for the native JavaScript encoding:
    ' becomes \x27
    " becomes \x22

    So your onclick would become:
    DoEdit('Preliminary Assessment \x22Mini\x22');

    This would work for example also when passing a JavaScript string as a parameter to another JavaScript method (alert() is an easy test method for this).

    I am referring you to the duplicate Stack Overflow question, How do I escape a string inside JavaScript code inside an onClick handler?.

    0 讨论(0)
  • 2020-11-22 11:57
    <html>
        <body>
            <a href="#" onclick="DoEdit('Preliminary Assessment &quot;Mini&quot;'); return false;">edit</a>
        </body>
    </html>
    

    Should do the trick.

    0 讨论(0)
  • 2020-11-22 11:58

    I have done a sample one using jQuery

    var descr = 'test"inside"outside';
    $(function(){
       $("#div1").append('<a href="#" onclick="DoEdit(descr);">Click Me</a>');       
    });
    
    function DoEdit(desc)
    {
        alert ( desc );
    }
    

    And this works in Internet Explorer and Firefox.

    0 讨论(0)
  • 2020-11-22 12:00

    You need to escape the string you are writing out into DoEdit to scrub out the double-quote characters. They are causing the onclick HTML attribute to close prematurely.

    Using the JavaScript escape character, \, isn't sufficient in the HTML context. You need to replace the double-quote with the proper XML entity representation, &quot;.

    0 讨论(0)
  • 2020-11-22 12:00

    This is how I do it, basically str.replace(/[\""]/g, '\\"').

    var display = document.getElementById('output');
    var str = 'class="whatever-foo__input" id="node-key"';
    display.innerHTML = str.replace(/[\""]/g, '\\"');
    
    //will return class=\"whatever-foo__input\" id=\"node-key\"
    <span id="output"></span>

    0 讨论(0)
提交回复
热议问题