EntryFieldDescription.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. 'use strict';
  2. var escapeHTML = require('../Utils').escapeHTML;
  3. /**
  4. * Create a linkified and HTML escaped entry field description.
  5. *
  6. * As a special feature, this description may contain both markdown
  7. * and plain <a href> links.
  8. *
  9. * @param {String} description
  10. */
  11. module.exports = function entryFieldDescription(description) {
  12. // we tokenize the description to extract text, HTML and markdown links
  13. // text and links are handled seperately
  14. var escaped = [];
  15. // match markdown [{TEXT}]({URL}) and HTML links <a href="{URL}">{TEXT}</a>
  16. var pattern = /(?:\[([^\]]+)\]\((https?:\/\/[^"<>\]]+)\))|(?:<a href="(https?:\/\/[^"<>]+)">([^<]*)<\/a>)/gi;
  17. var index = 0;
  18. var match;
  19. var link, text;
  20. while ((match = pattern.exec(description))) {
  21. // escape + insert text before match
  22. if (match.index > index) {
  23. escaped.push(escapeHTML(description.substring(index, match.index)));
  24. }
  25. link = match[2] || match[3];
  26. text = match[1] || match[4];
  27. // insert safe link
  28. escaped.push('<a href="' + link + '" target="_blank">' + escapeHTML(text) + '</a>');
  29. index = match.index + match[0].length;
  30. }
  31. // escape and insert text after last match
  32. if (index < description.length) {
  33. escaped.push(escapeHTML(description.substring(index)));
  34. }
  35. return '<div class="bpp-field-description">' + escaped.join('') + '</div>';
  36. };