I
I
Isaac Clark2015-03-11 14:45:40
JavaScript
Isaac Clark, 2015-03-11 14:45:40

How to decode a string that comes from the server?

Hello, tell me please.
On the server, as well as on the client, there is a check that if the user enters html tags, then they need to be encoded, the function looks like this:

var encodeHtmlEntities = function (str) {
    return String(str)
        .replace(/&/g, '&')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&apos;')
        .replace(/\\/g, '&bsol;')
        .replace(/\//g, '&sol;');
};

The problem is that the server also encodes messages before sending them, that is, I already receive this line: &lt;script&gt;alert(1)&lt;&sol;script&gt;
And if I insert it into ui, then it will be like this. And I need to make it look like this in ui.
<script>alert(1)</script>
I understand that I need to decode it first, and then encode it again and paste it into ui?
Question: should the decoding function look like?
Thanks for your help and your time.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Melnikov, 2015-03-11
@Dark_Knight

function encodeHtmlEntities(str) {
  return String(str)
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&apos;')
    .replace(/\\/g, '&bsol;')
    .replace(/\//g, '&sol;');
};

function decodeHtmlEntities(str) {
  return String(str)
    .replace(/&amp;/g, '&')
    .replace(/&lt;/g, '<')
    .replace(/&gt;/g, '>')
    .replace(/&quot;/g, '"')
    .replace(/&apos;/g, '\'')
    .replace(/&bsol;/g, '\\')
    .replace(/&sol;/g, '/');
};

var str = '<script src="test.com">\\Lorem Ipsu\'m</script>';
str = encodeHtmlEntities(str);
console.log(str); // &lt;script src=&quot;test.com&quot;&gt;&bsol;Lorem Ipsu&apos;m&lt;&sol;script&gt;
str = decodeHtmlEntities(str);
console.log(str); //  <script src="test.com">\Lorem Ipsu'm</script>

L
Leonid Sysoletin, 2015-03-11
@sysoletin

The decode function should look like the encode function. Just the opposite.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question