58

Possible Duplicate:
JavaScript/jQuery HTML Encoding

I have html tags need to be encoded.

<b>test</b>

I need to encode it to :

&lt;b&gt;test&lt;/b&gt;

I am using escape, but it doesn't work.

document.write(escape("<b>test</b>"));

the result I got is

%3Cb%3Etest%3C/b%3E

this is not what I expected. is there another way to do html encode using javascript?

2
  • 14
    this is NOT a duplicate. an answer is this: str => { let elt = document.createElement('span'); elt.textContent = str; return elt.innerHTML;} Commented Nov 12, 2018 at 20:23
  • document.write(('<b>test</b>').replace(/</g, '&lt;').replace(/>/g, '&gt;')); Commented Apr 18, 2019 at 12:17

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.