3

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.

2 Answers 2

4

You could try this:

npm install node-html-encoder

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

<%= encoder.htmlEncode('<foo /> "bar"') %>
Sign up to request clarification or add additional context in comments.

Comments

0

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!

2 Comments

-1 : Don't do things like this manually, because it's never as simple as it seems.
If you are going to encode attributes yourself, make sure you escape all the characters specified by OWASP

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.