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 "
.
You can do this in JavaScript like this:
const string = `This is a "cool" blog post`
return string.replace(/"/g, '"')
Which results in this valid attribute:
<div data-statement="This is a "cool" blog post" />
"
will be correctly parsed by JavaScript if you access it, for example like this:
document.querySelector('div').dataset.statement
Subscribe to my newsletter!
A weekly round-up of new blog posts and updates to projects I’m working on.