How to escape quotes in HTML attributes

If you use a quote mark (") in an HTML attribute, it'll interfere with the quotes surrounding the attribute. For example, this isn't valid:

<div data-statement="This is a "cool" blog post" />

To get around this, replace the quotes with &quot;.

You can do this in JavaScript like this:

const string = `This is a "cool" blog post`

return string.replace(/"/g, '&quot;')

Which results in this valid attribute:

<div data-statement="This is a &quot;cool&quot; blog post" />

&quot; will be correctly parsed by JavaScript if you access it, for example like this:

document.querySelector('div').dataset.statement

--

Last updated July 25, 2021