Код: Выделить всё
Text Editor with Toggle Bold/Italic
Bold
Italic
Send
body {
font-family: Arial, sans-serif;
text-align: center;
margin-top: 50px;
}
.editor-container {
display: inline-block;
text-align: left;
border: 1px solid #ccc;
padding: 10px;
width: 300px;
}
.toolbar {
margin-bottom: 5px;
}
.toolbar button {
margin-right: 5px;
padding: 5px 10px;
cursor: pointer;
}
.textbox {
width: 100%;
min-height: 100px;
border: 1px solid #ccc;
padding: 5px;
outline: none;
}
.output {
margin-top: 10px;
font-weight: bold;
}
.bold {
font-weight: bold;
}
.italic {
font-style: italic;
}
function toggleStyle(style) {
const selection = window.getSelection();
if (!selection.rangeCount) return;
const range = selection.getRangeAt(0);
const selectedText = range.toString().trim();
if (!selectedText) return;
let parentSpan = range.commonAncestorContainer.parentElement;
let shouldRemoveStyle = false;
if (parentSpan.tagName === "SPAN") {
if (parentSpan.classList.contains(style)) {
// Remove style if it's already applied
parentSpan.classList.remove(style);
shouldRemoveStyle = true;
}
}
if (!shouldRemoveStyle) {
// Apply new style only to selected text
const span = document.createElement("span");
span.classList.add(style);
span.textContent = selectedText;
range.deleteContents();
range.insertNode(span);
}
// Remove empty spans
document.querySelectorAll(".textbox span").forEach(el => {
if (el.classList.length === 0) {
el.replaceWith(el.textContent);
}
});
selection.removeAllRanges();
}
function convertToMarkdown() {
const textbox = document.getElementById("textbox");
let rawHTML = textbox.innerHTML;
// Step 1: Handle bold + italic first
rawHTML = rawHTML.replace(/(.*?)/g, "***$1***");
// Step 2: Handle only bold (after bold+italic is processed)
rawHTML = rawHTML.replace(/(.*?)/g, "**$1**");
// Step 3: Handle only italic (after bold+italic is processed)
rawHTML = rawHTML.replace(/(.*?)/g, "_$1_");
// Step 4: Ensure no redundant markdown (**_text_** → ***text***)
rawHTML = rawHTML.replace(/\*\*_([^_*]+)_\*\*/g, "***$1***");
rawHTML = rawHTML.replace(/_\*\*([^_*]+)\*\*_/g, "***$1***");
// Step 5: Ensure no extra symbols (fixes issues like __text****)
rawHTML = rawHTML.replace(/_{2,}([^_]+)_{2,}/g, "_$1_"); // Fixes __text__ → _text_
rawHTML = rawHTML.replace(/\*{4,}([^*]+)\*{4,}/g, "***$1***"); // Fixes ****text**** → ***text***
document.getElementById("output").innerText = "Markdown Output: " + rawHTML;
}
Подробнее здесь: https://stackoverflow.com/questions/794 ... and-italic