Reputation: 31861
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.
Upvotes: 3
Views: 4174
Reputation: 75666
You could try this:
npm install node-html-encoder
app.locals.encoder = require('node-html-encoder').Encoder;
<%= encoder.htmlEncode('<foo /> "bar"') %>
Upvotes: 4
Reputation: 11245
Short answer:
myString = myString.replace(/'|\\/g, '\\$&');
But if you need to escape HTML special characters too you can try:
myString = myString.replace(/&/g, '&');
myString = myString.replace(/</g, '<');
myString = myString.replace(/>/g, '>');
P.S. take care to not escape JavaScript operators using the replacements for HTML characters!
Upvotes: 0