Advertisement
Guest User

Toggle Underline Template for Templater

a guest
Oct 29th, 2024
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. /**
  2. * Templater Template for Obsidian - Text Underlining Toggle
  3. *
  4. * This template provides a toggle functionality for underlining selected text in Obsidian notes.
  5. * It handles the following operations:
  6. * 1. If text is not underlined: Adds HTML underlining tags and converts newlines to <br> tags
  7. * 2. If text is already underlined: Removes underlining and converts <br> tags back to newlines
  8. *
  9. * Usage:
  10. * 1. Select text in your Obsidian note
  11. * 2. Trigger this template
  12. * 3. The text will toggle between underlined and non-underlined states
  13. */
  14.  
  15. <%*
  16. // Get the currently selected text from the editor
  17. const text = tp.file.selection();
  18.  
  19. /**
  20. * Checks if the text already has HTML underlining tags
  21. * @param {string} text - The text to check
  22. * @returns {boolean} - True if text has underlining tags, false otherwise
  23. */
  24. const hasUnderlineTags = text => {
  25. return text.startsWith('<u>') && text.endsWith('</u>');
  26. };
  27.  
  28. /**
  29. * Converts newlines to HTML break tags
  30. * @param {string} text - The text to process
  31. * @returns {string} - Text with newlines replaced by <br> tags
  32. */
  33. const addBreakTags = text => {
  34. return text.replace(/\n/g, '<br>');
  35. };
  36.  
  37. /**
  38. * Converts HTML break tags back to newlines
  39. * @param {string} text - The text to process
  40. * @returns {string} - Text with <br> tags replaced by newlines
  41. */
  42. const removeBreakTags = text => {
  43. return text.replace(/<br>/g, '\n');
  44. };
  45.  
  46. let result;
  47. if (hasUnderlineTags(text)) {
  48. // If text is already underlined, remove the formatting
  49. result = text
  50. .replace('<u>', '') // Remove opening underline tag
  51. .replace('</u>', '') // Remove closing underline tag
  52. .replace(/<br>/g, '\n'); // Convert break tags back to newlines
  53. } else {
  54. // If text is not underlined, add the formatting
  55. result = `<u>${addBreakTags(text)}</u>`;
  56. }
  57.  
  58. // Return the processed text to replace the selection
  59. tR += result;
  60. %>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement