plaintexttohtml.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
  3. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
  4. */
  5. /**
  6. * @module clipboard/utils/plaintexttohtml
  7. */
  8. /**
  9. * Converts plain text to its HTML-ized version.
  10. *
  11. * @param {String} text The plain text to convert.
  12. * @returns {String} HTML generated from the plain text.
  13. */
  14. export default function plainTextToHtml( text ) {
  15. text = text
  16. // Encode <>.
  17. .replace( /</g, '&lt;' )
  18. .replace( />/g, '&gt;' )
  19. // Creates a paragraph for each double line break.
  20. .replace( /\r?\n\r?\n/g, '</p><p>' )
  21. // Creates a line break for each single line break.
  22. .replace( /\r?\n/g, '<br>' )
  23. // Preserve trailing spaces (only the first and last one – the rest is handled below).
  24. .replace( /^\s/, '&nbsp;' )
  25. .replace( /\s$/, '&nbsp;' )
  26. // Preserve other subsequent spaces now.
  27. .replace( /\s\s/g, ' &nbsp;' );
  28. if ( text.includes( '</p><p>' ) || text.includes( '<br>' ) ) {
  29. // If we created paragraphs above, add the trailing ones.
  30. text = `<p>${ text }</p>`;
  31. }
  32. // TODO:
  33. // * What about '\nfoo' vs ' foo'?
  34. return text;
  35. }