I have strings like
var str = 'One & two & three';
rendered into HTML by the web server. I need to transform those strings into
'One & two & three'
Currently, that's what I am doing (with help of jQuery):
$(document.createElement('div')).html('{{ driver.person.name }}').text()
However I have an unsettling feeling that I am doing it wrong. I have tried
unescape("&")
but it doesn't seem to work, neither do decodeURI/decodeURIComponent.
Are there any other, more native and elegant ways of doing so?
element.innerText
also does the trick.First create a
<span id="decodeIt" style="display:none;"></span>
somewhere in the bodyNext, assign the string to be decoded as innerHTML to this:
Finally,
Here is the overall code:
Do you need to decode all encoded HTML entities or just
&
itself?If you only need to handle
&
then you can do this:If you need to decode all HTML entities then you can do it without jQuery:
Please take note of Mark's comments below which highlight security holes in an earlier version of this answer and recommend using
textarea
rather thandiv
to mitigate against potential XSS vulnerabilities. These vulnerabilities exist whether you use jQuery or plain JavaScript.A more modern option for interpreting HTML (text and otherwise) from JavaScript is the HTML support in the
DOMParser
API (see here in MDN). This allows you to use the browser's native HTML parser to convert a string to an HTML document. It has been supported in new versions of all major browsers since late 2014.If we just want to decode some text content, we can put it as the sole content in a document body, parse the document, and pull out the its
.body.textContent
.We can see in the draft specification for
DOMParser
that JavaScript is not enabled for the parsed document, so we can perform this text conversion without security concerns.It's beyond the scope of this question, but please note that if you're taking the parsed DOM nodes themselves (not just their text content) and moving them to the live document DOM, it's possible that their scripting would be reenabled, and there could be security concerns. I haven't researched it, so please exercise caution.
a javascript solution that catches the common ones:
this is the reverse of https://stackoverflow.com/a/4835406/2738039
I tried everything to remove & from a JSON array. None of the above examples, but https://stackoverflow.com/users/2030321/chris gave a great solution that led me to fix my problem.
I did not use, because I did not understand how to insert it into a modal window that was pulling JSON data into an array, but I did try this based upon the example, and it worked:
I like it because it was simple, and it works, but not sure why it's not widely used. Searched hi & low to find a simple solution. I continue to seek understanding of the syntax, and if there is any risk to using this. Have not found anything yet.