edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31861

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.

Upvotes: 3

Views: 4174

Answers (2)

chovy
chovy

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

micnic
micnic

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, '&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!

Upvotes: 0

Related Questions