How can I convert string returned from API call to proper HTML in javascript?

I am calling an API command(“@ReportProperty2(45899,exportdata,‘16115898’)@”) which returns HTML of the button but in string format and > and < are in > and < and there are double quotes are well which breaks my code at the following line:

const aaa = "@ReportProperty2(45899,exportdata,,'16115898')@";

RESULT FROM THE COMMAND: “<button type=button class=Button onclick=“openwp(‘1677008’,‘RHpdFBx7GS9YGFEwFmUUCyE4Ih8lHyA!H2JbUENBa1BV’)” ><i class=“fa fa-pencil-square-o” style=“margin: 0 4px 0 0”></i>Enter Budget</button>”

I have tried replacing but it is throwing “unexpected token: identifier” error.

How can I convert the result to the following:

<button type="button" class="Button" onclick="openwp('1677008','RHpdFBx7GS9YGFEwFmUUCyE4Ih8lHyA!H2JbUENBa1BV')"><i class="fa fa-pencil-square-o" style="margin: 0 4px 0 0" data-original-title="" title=""></i>Enter Budget</button>

Hi @asifakhtar, there seems to be some loss of information…

You mean escaped as HTML entities (&lt; and &gt;) or URL encoded (%3C and %3e)?

Is that the exact response, including the wrapping quotes? In this case the response might be supposed to be a JSON string… so we’d need to know 1) what the Content-Type header of the response is, 2) how openwp() processes the response, and 3) how you are eventually attempting to insert the response body into the DOM.

Replacing what? :-)

exact response is:

"&lt;button type=button class=Button onclick="openwp('1677008','RHpdFBx7GS9YGFEwFmUUCyE4Ih8lHyA!H2JbUENBa1BV')" &gt;&lt;i class="fa fa-pencil-square-o" style="margin: 0 4px 0 0"&gt;&lt;/i&gt;Enter Budget&lt;/button&gt;"

The HTML entities can be accounted for by setting it as the inner HTML of a (temporary) element, and then reading that element’s text content… e.g.:

const tmp = document.createElement('div')

tmp.innerHTML = '&lt;p&gt;hello world&lt;/p&gt;'
console.log(tmp.textContent) // <p>hello world</p>

As for the quotes I’m not really sure, the response is wrapped in regular double quotes and also includes unescaped double quotes? Or is this maybe supposed to be a JSON string? In this case you might just parse it like so:

tmp.innerHTML = JSON.parse(response)
console.log(tmp.textContent) // Should now give you the desired output

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.