How to easily convert api data to html (in a general fashion)
-
We are building some high-level hooks in our web app to monitor certain activity in the NodeBB forum that we will instantiate.
So as we see in the following the nodebb api will return characters such as & as &.
When I attempt to display this string in my webapp, I need to convert this so it doesn't do the following
Can you recommend a generalized way for me to handle such content received via the API (so that the special characters found in the API response are properly converted to displayable text)?
I'd rather not build special case logic to deal with such things.
-
Thanks @baris Is "validator" a standard javascript utility that can be used in the front end? Or perhaps is it part of an npm component that I can simply install? If so is there a method to "unescape"?
I dont recognize "validator".. nor does google take me to an answer to the above question.
-
https://github.com/validatorjs/validator.js
is this the tool you use?
-
@baris yay!! validator.unescape() worked for me
-
-
Hi. I wanted to revisit this momentarily. I am now receiving posts. I've noticed that the "content field" is escaped. I assumed that I could unescape using the validator. However the escape characters remain after I unescape.
Thoughts on this one?
-
@David-Sargrad it sounds like however you're displaying these is escaping the text. What framework are you using?
-
@PitaJ its not the display mechanism that is escaping these. The NodeBB api escapes these; using the validator linked above. I have used that same validator to unescape some of the fields received from the NodeBB API (e.g. the title of the category). However for some odd reason the content field is not being stripped of the escape characters when I use the validator.unescape(content) call.
-
@PitaJ I think you are actually right.. my issue is likely the way I am saving that content into a javascript variable.. i think i'm saving it as a string or something, and javascript then escapes..
-
@David-Sargrad JavaScript won't escape things randomly. How are you outputting the HTML from the API into the web page? Frameworks like react etc will automatically escape things just like you're seeing.
-
@PitaJ .. so i am using react.. and you are absolutely right.. I wasnt quite sure how to output it..
Right now I'm trying the following: but of course that doesnt work.const cool = (<div> {content} </div>); <React.Fragment>{cool}</React.Fragment>
It simply displays the string as follows:
I've been trying to get some ideas here:
https://javascript.plainenglish.io/how-to-convert-html-strings-to-jsx-with-react-ae1afab29a03Gonna try this:
https://stackoverflow.com/a/45058774 -
That actually worked.
-
@PitaJ Ty.. You steered me straight!
-