Escape Quotes In HTML5 Data Attribute Using Javascript

前端 未结 9 2135
春和景丽
春和景丽 2020-12-30 20:47

I\'m using jQuery\'s .data() to work with custom HTML5 data attributes where the value of the attribute needs to be able to contain both single quotes and doubl

相关标签:
9条回答
  • 2020-12-30 21:30

    For it to be proper html, you have to escape the troublesome characters. I'd escape them with HTML entities. This means that whatever tool is being used to input this information would have have to store them properly and/or the tool retrieving them on the back end would have to escape them.

    Then if you want to use them in your JS, you'd have to run some find-and-replace functions to convert the characters back into HTML and quotes.

    Most back-end dev languages have some sort of 'htmlescape/unescape' functionality, so that shouldn't be to hard.

    To unescape it via jQuery, here's something found via a quick Google: http://www.naveen.com.au/javascript/jquery/encode-or-decode-html-entities-with-jquery/289

    0 讨论(0)
  • 2020-12-30 21:34

    If you are using Lodash, then you can use _.escape() and _.unescape(). It converts the characters "&", "<", ">", '"', and "'" in string to their corresponding HTML entities.

    Reference : https://lodash.com/docs/#escape

    0 讨论(0)
  • 2020-12-30 21:37

    Use encodeURI to escape quotation marks in your JSON object. Parse the string with decodeURI.

    var popup = document.getElementById('popup'),
        msgObj = JSON.parse(decodeURI(popup.dataset.message));
    
    console.log(msgObj);
    <a id="popup" href="#" data-message="%7B%22title%22:%22Print%22,%22message%22:%22Printing%20not%20yet%20implemented%22%7D" />

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