This tutorial gives you examples how to perform HTML encode in Dart, including how to set which characters will be escaped.
The class we're going to use is HtmlEscape
, which is available in import 'dart:convert'
library.
import 'dart:convert' show HtmlEscape, HtmlEscapeMode;
void main() {
String unsafeHtml = 'Welcome to <a href="https://www.woolha.com">woolha.com</a>. The \'cutest\' programming blog ever.';
HtmlEscape htmlEscape = const HtmlEscape();
print(htmlEscape.convert(unsafeHtml));
}
The output is:
Welcome to <a href="https://www.woolha.com">woolha.com</a>. The 'cutest' programming blog ever.
By default, Dart will escape <
& >
, "
(double quote), '
(apostrophe), and /
(slash). However, you can choose what you want to escape by passing an optional parameter to the HtmlEscape
whose type is HtmlEscapeMode
. Below are list of modes provided by Dart along with what characters are escaped by each mode.
Mode | < & > |
" (double quote) |
' (apostrophe) |
/ (slash) |
---|---|---|---|---|
unknown (default) |
✔ | ✔ | ✔ | ✔ |
attribute (default) |
✔ | ✔ | ✘ | ✘ |
sqAttribute (default) |
✔ | ✘ | ✔ | ✘ |
element (default) |
✔ | ✘ | ✘ | ✘ |
HtmlEscape htmlEscape = const HtmlEscape(HtmlEscapeMode.element);
The output is:
Welcome to <a href="https://www.woolha.com">woolha.com</a>. The 'cutest' programming blog ever.
If you need custom mode, for example you want to escape only double quote, you can create a new HtmlEscapeMode
.
const HtmlEscapeMode customMode = const HtmlEscapeMode(name: 'doubleQuoteOnly', escapeQuot: true);
HtmlEscape htmlEscape = const HtmlEscape(customMode);
The output is:
Welcome to <a href="https://www.woolha.com">woolha.com</a>. The 'cutest' programming blog ever.
Please note that, if you call element.setInnerHtml
, Dart will automatically sanitize unsafe string. Therefore, you don't need to manually escape the HTML.