Guest User

Untitled

a guest
Aug 7th, 2025
22
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. javascript:(function () {
  2.   const bookmarkletName = 'BBCode Formatter';
  3.   const description = 'Formats BBCode in textareas and editors without breaking inline tag structures.';
  4.   console.log(`%c${bookmarkletName}`, 'font-weight: bold; color: green;', `– ${description}`);
  5.  
  6.   function formatBBCode(text) {
  7.     return text
  8.      
  9.       .replace(/\[HEADING=2\]/g, '\n\n[HEADING=2]')
  10.       .replace(/\[\/HEADING\]/g, '[/HEADING]\n\n')
  11.  
  12.      
  13.       .replace(/\[LIST\]/g, '\n\n[LIST]')
  14.       .replace(/\[\/LIST\]/g, '[/LIST]\n\n')
  15.       .replace(/\[\*\]/g, '\n[*]')
  16.  
  17.      
  18.       .replace(/\[\/IMG\](?!\s*\[\/URL\])/gi, '[/IMG]\n\n')
  19.  
  20.      
  21.       .replace(/\r\n/g, '\n')
  22.       .replace(/\r/g, '\n')
  23.  
  24.      
  25.       .replace(/\n{3,}/g, '\n\n');
  26.   }
  27.  
  28.   const activeEl = document.activeElement;
  29.   const isTextInput = activeEl && (
  30.     activeEl.tagName === 'TEXTAREA' ||
  31.     (activeEl.tagName === 'INPUT' && activeEl.type === 'text') ||
  32.     activeEl.isContentEditable
  33.   );
  34.  
  35.   if (!isTextInput) {
  36.     console.warn('No editable text area is focused.');
  37.     return;
  38.   }
  39.  
  40.   let originalText = activeEl.value || activeEl.innerText || '';
  41.   let formattedText = '';
  42.   const selectionStart = activeEl.selectionStart;
  43.   const selectionEnd = activeEl.selectionEnd;
  44.  
  45.   if (typeof selectionStart === 'number' && typeof selectionEnd === 'number' && selectionStart !== selectionEnd) {
  46.     const before = originalText.slice(0, selectionStart);
  47.     const selected = originalText.slice(selectionStart, selectionEnd);
  48.     const after = originalText.slice(selectionEnd);
  49.     const formattedSelection = formatBBCode(selected);
  50.     formattedText = before + formattedSelection + after;
  51.  
  52.     activeEl.value = formattedText;
  53.     activeEl.setSelectionRange(before.length, before.length + formattedSelection.length);
  54.   } else {
  55.     formattedText = formatBBCode(originalText);
  56.     if (activeEl.value !== undefined) {
  57.       activeEl.value = formattedText;
  58.     } else {
  59.       activeEl.innerText = formattedText;
  60.     }
  61.   }
  62.  
  63.   console.log('✅ BBCode formatted successfully.');
  64. })();
  65.  
Advertisement
Add Comment
Please, Sign In to add comment