1

I have express application, and EJS as view engine. I am trying to set some html to div in 2 different ways:

const attachmentFileNames = '<%= eco.attachmentFileName %>';
if (attachmentFileNames) {
    $("#attachmentFileNameList").html(attachmentFileNames.replace(',', '<br/>'));
}

and

const attachmentFileNames = "<%= eco.attachmentFileName ? eco.attachmentFileName.replace(',', '<br/>') : '' %>";
if (attachmentFileNames) {
    $("#attachmentFileNameList").html(attachmentFileNames);
}

The thing is that first peace of code is working as expected ('< br/>' is treated as line terminator), but the second one just sets all data as a text ('< br/>' is displayed as string).

Could anybody please explain that?

1 Answer 1

1

It's not jQuery's html function, it's EJS, which is automatically escaping the text produced by your <%= ... %> expression.

In your second example, if you look at the value of attachmentFileNames in the debugger, you'll presumably see &lt;br/> (or &lt;br/&gt;) instead of <br/>. When you use "&lt;br/>" (or "&lt;br/&gt;") as HTML, the result is the characters <, b, r, /, and >:

const attachmentFileNames1 = 'one,two';
if (attachmentFileNames1) {
    $("#attachmentFileNameList1").html(attachmentFileNames1.replace(',', '<br/>'));
}

const attachmentFileNames2 = 'one&lt;br/>two';
if (attachmentFileNames2) {
    $("#attachmentFileNameList2").html(attachmentFileNames2);
}
<div id="attachmentFileNameList1"></div>
<div id="attachmentFileNameList2"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.