Ben Borgers

How to escape quotes in HTML attributes

July 25, 2021

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:


Subscribe to my newsletter!

A weekly round-up of new blog posts and updates to projects I’m working on.