plaintexttohtml.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. /**
  2. * @license Copyright (c) 2003-2019, 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 paragraphs for double line breaks and change single line breaks to <br>s.
  20. .replace( /\n\n/g, '</p><p>' )
  21. .replace( /\n/g, '<br>' )
  22. // Preserve trailing spaces (only the first and last one – the rest is handled below).
  23. .replace( /^\s/, '&nbsp;' )
  24. .replace( /\s$/, '&nbsp;' )
  25. // Preserve other subsequent spaces now.
  26. .replace( /\s\s/g, ' &nbsp;' );
  27. if ( text.indexOf( '</p><p>' ) > -1 ) {
  28. // If we created paragraphs above, add the trailing ones.
  29. text = `<p>${ text }</p>`;
  30. }
  31. // TODO:
  32. // * What about '\nfoo' vs ' foo'?
  33. return text;
  34. }