0

My question is based on the great answer from this SO question How to encode a string in JavaScript for displaying in HTML?

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

I need the same but should keep each "<br>" substring in the string. Looking for the best way to modify the function htmlEntities then.

Thank you.

Community
  • 1
  • 1
Haradzieniec
  • 8,150
  • 26
  • 100
  • 199

3 Answers3

0

Anything smarter than my solution?

function htmlEntitiesModified(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace('&lt;br&gt;', '<br>');
}

//.replace('&lt;br&gt;', '<br>') was added to the end.

Please vote if this solution is elegant and good enough so I know. Thank you.

Haradzieniec
  • 8,150
  • 26
  • 100
  • 199
0

Try

function htmlEntities(str) {
        return String(str)
               .replace(/&/g, '&amp;')
               .replace(/<[^<br]/g, '&lt;') // negate `<br`
               .replace(/[^br+| \/>]>/g, '&gt;') // negate `br>` or `br />`
               .replace(/"/g, '&quot;');
    }

var unsafestring = "<br><oohlook&atme><br><br />string";
function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/<[^<br]/g, '&lt;').replace(/[^br+| \/>]>/g, '&gt;').replace(/"/g, '&quot;');
}
document.body.innerText = htmlEntities(unsafestring);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
guest271314
  • 1
  • 10
  • 82
  • 156
0

I'm very surprised no one answered this. You can just use the browser it self to do the escaping for you. No regex is better or safer than letting the browser do what it does best, handle HTML.

function escapeHTML(str){
    var p = document.createElement("p");
    p.appendChild(document.createTextNode(str));
    return p.innerHTML;
}

or a short alternative using the Option() constructor

function escapeHTML(str){
    return new Option(str).innerHTML;
}
Vitim.us
  • 16,145
  • 12
  • 81
  • 96