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 "
.
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;