user3758078
user3758078

Reputation:

Storing HTML Within Attribute

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?

Upvotes: 1

Views: 167

Answers (1)

gurvinder372
gurvinder372

Reputation: 68393

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

Upvotes: 1

Related Questions