I have a localStorage holding a string that looks like the follows:
"ABC&nbps;&nbps;&nbps;&nbps;ABC Description"
I get this string from the localStorage and I need to set the value of this string into an Option of a drop-down control, replacing the no-break space entity with empty spaces (in order to align with other options).
In the code behind of ASP.NET I would use HttpUtility.HtmlDecode. But how do you decode this string in the javascript?
I have a localStorage holding a string that looks like the follows:
"ABC&nbps;&nbps;&nbps;&nbps;ABC Description"
I get this string from the localStorage and I need to set the value of this string into an Option of a drop-down control, replacing the no-break space entity with empty spaces (in order to align with other options).
In the code behind of ASP.NET I would use HttpUtility.HtmlDecode. But how do you decode this string in the javascript?
Share Improve this question asked Nov 29, 2015 at 1:08 HidalgoHidalgo 9412 gold badges14 silver badges41 bronze badges 1- Possible duplicate of HTML Entity Decode – jacmkno Commented Nov 29, 2015 at 1:32
3 Answers
Reset to default 4You can use the following bit of code to convert HTML to text (using just javascript)
var span = document.createElement("SPAN");
span.innerHTML = "ABC ABC Description";
alert(span.innerText);
It creates a dummy element, sets its HTML to your HTML and extracts the text.
Note that it should be nbsp
(non-breaking space) and not nbps
That said, the way you are doing this suggests that you are allowing the user to enter arbitrary HTML. This is not a good idea in terms of security (a user could put in malicious HTML into this field).
This was answered before here. But it's
not &nbps;
. To decode wrong markup with &nbps;
on it, you will have to do a manual replace: whatever.replace('&nbps;', ' ');
It's safer to strip script tags instead of having the browser parse the raw HTML. That will prevent malicious code from being executed...
var decodeEntities = (function() {
// this prevents any overhead from creating the object each time
var element = document.createElement('div');
function decodeHTMLEntities (str) {
if(str && typeof str === 'string') {
// strip script/html tags
str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
}
return str;
}
return decodeHTMLEntities;
})();
http://jsfiddle/LYteC/4/
If you are using Jquery on the client side use this to convert into html.
theHtml = $.parseHTML( "ABC ABC Description" );