How do I encode an HTML element attribute

How do I encode an HTML attribute from an EJS template in NodeJS. I need to do something like:

<img onmouseover=<% myString %> />

Where myString would then be properly escape and quoted to be a valid attribute.

You could try this:

npm install node-html-encoder

app.locals.encoder = require('node-html-encoder').Encoder;

<%= encoder.htmlEncode('<foo /> "bar"') %>

Short answer:

myString = myString.replace(/'|\\/g, '\\$&');

But if you need to escape HTML special characters too you can try:

myString = myString.replace(/&/g, '&amp;');
myString = myString.replace(/</g, '&lt;');
myString = myString.replace(/>/g, '&gt;');

P.S. take care to not escape JavaScript operators using the replacements for HTML characters!