Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I escape a string for HTML?

Tags:

dart

I have a string that might contain unsafe HTML. I want to escape the tags in the string, changing <script> to &lt;script&gt;

How can I do this with Dart?

like image 518
Seth Ladd Avatar asked Dec 12 '13 19:12

Seth Ladd


1 Answers

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 &lt;script&gt;world&lt;&#x2F;script&gt;

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.

like image 132
Seth Ladd Avatar answered Oct 05 '22 08:10

Seth Ladd