unescape static method
Converts HTML entities to their corresponding characters.
Handles both named entities (e.g., &, <, ) and
numeric entities (e.g., A, A).
Returns null if the input is null or empty.
Supported named entities include:
- Basic:
&,<,>,",',' - Whitespace:
- Symbols:
©,®,™,•,… - Currency:
€,£,¥,¢ - Punctuation:
–,—,‘,’,“,” - Math:
×,÷,±,½,¼,¾ - And more...
Example:
HtmlUtils.unescape('<div>'); // '<div>'
HtmlUtils.unescape('&amp;'); // '&'
HtmlUtils.unescape('A'); // 'A'
HtmlUtils.unescape('A'); // 'A'
HtmlUtils.unescape('Hello World'); // 'Hello World'
HtmlUtils.unescape('© 2024'); // '© 2024'
Implementation
static String? unescape(String? htmlText) {
if (htmlText == null || htmlText.isEmpty) {
return null;
}
String result = htmlText;
// Replace named entities
_htmlEntities.forEach((String entity, String char) {
result = result.replaceAll(entity, char);
});
// Replace numeric entities (decimal and hex)
result = result.replaceAllMapped(_numericEntityRegex, (Match match) {
final String? decimal = match.group(1);
final String? hex = match.group(2);
int? codePoint;
if (decimal != null) {
codePoint = int.tryParse(decimal);
} else if (hex != null) {
codePoint = int.tryParse(hex, radix: 16);
}
if (codePoint != null && codePoint > 0 && codePoint <= 0x10FFFF) {
return String.fromCharCode(codePoint);
}
return match.group(0) ?? ''; // Return original if invalid
});
return result;
}