Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- javascript:(function () {
- const bookmarkletName = 'BBCode Formatter';
- const description = 'Formats BBCode in textareas and editors without breaking inline tag structures.';
- console.log(`%c${bookmarkletName}`, 'font-weight: bold; color: green;', `– ${description}`);
- function formatBBCode(text) {
- return text
- .replace(/\[HEADING=2\]/g, '\n\n[HEADING=2]')
- .replace(/\[\/HEADING\]/g, '[/HEADING]\n\n')
- .replace(/\[LIST\]/g, '\n\n[LIST]')
- .replace(/\[\/LIST\]/g, '[/LIST]\n\n')
- .replace(/\[\*\]/g, '\n[*]')
- .replace(/\[\/IMG\](?!\s*\[\/URL\])/gi, '[/IMG]\n\n')
- .replace(/\r\n/g, '\n')
- .replace(/\r/g, '\n')
- .replace(/\n{3,}/g, '\n\n');
- }
- const activeEl = document.activeElement;
- const isTextInput = activeEl && (
- activeEl.tagName === 'TEXTAREA' ||
- (activeEl.tagName === 'INPUT' && activeEl.type === 'text') ||
- activeEl.isContentEditable
- );
- if (!isTextInput) {
- console.warn('No editable text area is focused.');
- return;
- }
- let originalText = activeEl.value || activeEl.innerText || '';
- let formattedText = '';
- const selectionStart = activeEl.selectionStart;
- const selectionEnd = activeEl.selectionEnd;
- if (typeof selectionStart === 'number' && typeof selectionEnd === 'number' && selectionStart !== selectionEnd) {
- const before = originalText.slice(0, selectionStart);
- const selected = originalText.slice(selectionStart, selectionEnd);
- const after = originalText.slice(selectionEnd);
- const formattedSelection = formatBBCode(selected);
- formattedText = before + formattedSelection + after;
- activeEl.value = formattedText;
- activeEl.setSelectionRange(before.length, before.length + formattedSelection.length);
- } else {
- formattedText = formatBBCode(originalText);
- if (activeEl.value !== undefined) {
- activeEl.value = formattedText;
- } else {
- activeEl.innerText = formattedText;
- }
- }
- console.log('✅ BBCode formatted successfully.');
- })();
Advertisement
Add Comment
Please, Sign In to add comment