util.dart 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import 'dart:convert';
  2. import 'package:charcode/charcode.dart';
  3. String escapeHtml(String html) =>
  4. const HtmlEscape(HtmlEscapeMode.element).convert(html);
  5. // Escape the contents of [value], so that it may be used as an HTML attribute.
  6. // Based on http://spec.commonmark.org/0.28/#backslash-escapes.
  7. String escapeAttribute(String value) {
  8. final result = StringBuffer();
  9. int ch;
  10. for (var i = 0; i < value.codeUnits.length; i++) {
  11. ch = value.codeUnitAt(i);
  12. if (ch == $backslash) {
  13. i++;
  14. if (i == value.codeUnits.length) {
  15. result.writeCharCode(ch);
  16. break;
  17. }
  18. ch = value.codeUnitAt(i);
  19. switch (ch) {
  20. case $quote:
  21. result.write('&quot;');
  22. break;
  23. case $exclamation:
  24. case $hash:
  25. case $dollar:
  26. case $percent:
  27. case $ampersand:
  28. case $apostrophe:
  29. case $lparen:
  30. case $rparen:
  31. case $asterisk:
  32. case $plus:
  33. case $comma:
  34. case $dash:
  35. case $dot:
  36. case $slash:
  37. case $colon:
  38. case $semicolon:
  39. case $lt:
  40. case $equal:
  41. case $gt:
  42. case $question:
  43. case $at:
  44. case $lbracket:
  45. case $backslash:
  46. case $rbracket:
  47. case $caret:
  48. case $underscore:
  49. case $backquote:
  50. case $lbrace:
  51. case $bar:
  52. case $rbrace:
  53. case $tilde:
  54. result.writeCharCode(ch);
  55. break;
  56. default:
  57. result.write('%5C');
  58. result.writeCharCode(ch);
  59. }
  60. } else if (ch == $quote) {
  61. result.write('%22');
  62. } else {
  63. result.writeCharCode(ch);
  64. }
  65. }
  66. return result.toString();
  67. }