1

I'm storing HTML code within an element attribute like so.

<div data-html-code="<iframe width="560" height="315" src="https://www.youtube.com/embed/sNhhvQGsMEc" frameborder="0" allowfullscreen></iframe>"></div>

How can I escape all the necessary characters to make this valid using jQuery/Javascript?

3
  • 1
    replace double quotes with single quote or by escape them by \" \". Like this : jsfiddle.net/DinoMyte/c8jzo021 Commented Feb 9, 2016 at 18:11
  • use single quotes like this <div data-html-code='<iframe width="560" height="315" src="https://www.youtube.com/embed/sNhhvQGsMEc" frameborder="0" allowfullscreen></iframe>'></div> Commented Feb 9, 2016 at 18:12
  • How do I do this dynamically, When code is entered in an input field? Also would escaping '<', '>' also be necessary? Commented Feb 9, 2016 at 18:15

1 Answer 1

1

use this htmlEscape method

function htmlEscape(str) {
    return String(str)
            .replace(/&/g, '&amp;')
            .replace(/"/g, '&quot;')
            .replace(/'/g, '&#39;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;');
}

this should give you a string that can be used as a valid html attribute value

Sign up to request clarification or add additional context in comments.

Comments