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?
I found that you sometimes don't need to do the encode and decode if you restrict the character set by adding the following meta attribute.
This is from ExtJS source code.
In case you're looking for it, like me - meanwhile there's a nice and safe JQuery method.
https://api.jquery.com/jquery.parsehtml/
You can f.ex. type this in your console:
So $.parseHTML(x) returns an array, and if you have HTML markup within your text, the array.length will be greater than 1.
You can use Lodash unescape / escape function https://lodash.com/docs/4.17.5#unescape
str will become
'fred, barney, & pebbles'
Matthias Bynens has a library for this: https://github.com/mathiasbynens/he
Example:
I suggest favouring it over hacks involving setting an element's HTML content and then reading back its text content. Such approaches can work, but are deceptively dangerous and present XSS opportunities if used on untrusted user input.
If you really can't bear to load in a library, you can use the
textarea
hack described in this answer to a near-duplicate question, which, unlike various similar approaches that have been suggested, has no security holes that I know of:But take note of the security issues, affecting similar approaches to this one, that I list in the linked answer! This approach is a hack, and future changes to the permissible content of a
textarea
(or bugs in particular browsers) could lead to code that relies upon it suddenly having an XSS hole one day.jQuery will encode and decode for you. However, you need to use a textarea tag, not a div.