I have a string that might contain unsafe HTML. I want to escape the tags in the string, changing <script>
to <script>
How can I do this with Dart?
Use HtmlEscape from dart:convert
.
import 'dart:convert' show HtmlEscape;
void main() {
var unsafe = 'Hello <script>world</script>';
var sanitizer = const HtmlEscape();
print(sanitizer.convert(unsafe));
}
The above app prints:
Hello <script>world</script>
The default behavior is to escape apostrophes, greater-than/less-than, quotes, and slashes.
If you want to control what is escaped, you can create a new HtmlEscape
with a HtmlEscapeMode.
For example, to escape only greater-than/less-than and slashes, try this:
var sanitizer = const HtmlEscape(HtmlEscapeMode.ELEMENT);
Remember, Dart automatically sanitizes strings before they get into HTML. So you may not need to manually escape the HTML script. If you call element.setInnerHtml
with an unsafe string, it will get sanitized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With