You're correct—the current Markdown parser in your Dracula Markdown Editor doesn't handle image syntax (). To enable image rendering, you'll need to update the processInline function within your JavaScript to recognize and convert image Markdown syntax into corresponding HTML <img> tags.
Here's how you can modify your existing code to handle images:
-
Update the processInline Function:
Add a regular expression to detect image syntax and replace it with an <img> HTML tag. Place this replacement before the link replacement to ensure that image links are processed correctly without being mistaken for regular links.
-
Ensure Proper Escaping:
Since you're handling user-generated content, it's essential to sanitize inputs to prevent potential security issues like Cross-Site Scripting (XSS). However, since images are being processed and directly inserted as <img> tags, ensure that only safe URLs are allowed or implement additional sanitization as needed.
-
Optional CSS Styling:
You might want to style the images for better appearance within the preview pane. For example, you can set a maximum width to ensure images don't overflow their container.
Updated Code with Image Handling
Below is the complete HTML file with the necessary modifications highlighted:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dracula Markdown Editor</title>
<style>
/* Dracula Theme Colors */
:root {
--background: #282a36;
--current-line: #44475a;
--foreground: #f8f8f2;
--selection: #44475a;
--comment: #6272a4;
--cyan: #8be9fd;
--green: #50fa7b;
--orange: #ffb86c;
--pink: #ff79c6;
--purple: #bd93f9;
--red: #ff5555;
--yellow: #f1fa8c;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
height: 100vh;
background-color: var(--background);
color: var(--foreground);
display: flex;
flex-direction: column;
}
header {
padding: 1rem;
background-color: var(--current-line);
text-align: center;
font-size: 1.5rem;
font-weight: bold;
border-bottom: 1px solid var(--foreground);
}
main {
flex: 1;
display: flex;
overflow: hidden;
}
.editor, .preview {
width: 50%;
padding: 1rem;
height: 100%;
overflow: auto;
}
.editor {
background-color: var(--current-line);
border-right: 1px solid var(--foreground);
}
.editor textarea {
width: 100%;
height: 100%;
background-color: var(--current-line);
color: var(--foreground);
border: none;
resize: none;
font-size: 1rem;
line-height: 1.5;
font-family: 'Courier New', Courier, monospace;
outline: none;
}
.preview {
background-color: var(--background);
}
/* Markdown Styling */
.preview h1 {
color: var(--pink);
border-bottom: 2px solid var(--foreground);
padding-bottom: 0.3em;
margin-bottom: 0.5em;
}
.preview h2 {
color: var(--pink);
border-bottom: 1px solid var(--foreground);
padding-bottom: 0.3em;
margin-bottom: 0.5em;
}
.preview h3 {
color: var(--pink);
margin-bottom: 0.5em;
}
.preview p {
margin-bottom: 1em;
line-height: 1.6;
}
.preview a {
color: var(--cyan);
text-decoration: none;
}
.preview a:hover {
text-decoration: underline;
}
.preview strong {
color: var(--yellow);
}
.preview em {
color: var(--green);
}
.preview code {
background-color: var(--selection);
color: var(--purple);
padding: 0.2em 0.4em;
border-radius: 4px;
font-family: 'Courier New', Courier, monospace;
}
.preview pre {
background-color: var(--selection);
color: var(--purple);
padding: 1em;
border-radius: 4px;
overflow-x: auto;
font-family: 'Courier New', Courier, monospace;
margin-bottom: 1em;
}
.preview blockquote {
border-left: 4px solid var(--comment);
color: var(--comment);
padding-left: 1em;
margin-left: 0;
margin-right: 0;
font-style: italic;
}
.preview ul, .preview ol {
margin-bottom: 1em;
padding-left: 1.5em;
}
.preview li {
margin-bottom: 0.5em;
}
/* Horizontal Rule Styling */
.preview hr {
border: none;
border-top: 1px solid var(--foreground);
margin: 1em 0;
}
/* Optional: Style images within the preview */
.preview img {
max-width: 100%;
height: auto;
display: block;
margin: 1em 0;
border-radius: 4px;
}
</style>
</head>
<body>
<header>Dracula Markdown Editor</header>
<main>
<div class="editor">
<textarea id="markdown" placeholder="Type your markdown here...">
# Welcome to the Dracula Markdown Editor
Hello! 👋
This **Markdown editor** provides a smooth and efficient way to write and preview your Markdown content in real-time. Enjoy a visually appealing experience with the Dracula dark theme.
## Features
- **Real-time Preview:** See your formatted text as you type.
- **Syntax Highlighting:** Write code snippets with syntax highlighting support.
- **Nested Lists:** Create complex lists effortlessly.
- **Inline Styling:** Use *italic*, **bold**, and ***combined*** text styles.
- **Links and Images:** Easily add [links](https://www.example.com) and images.
- **Blockquotes:** Highlight important sections with blockquotes.
- **Horizontal Rules:** Separate content neatly with horizontal lines.
## Getting Started
### Writing Text
You can write regular text, and apply formatting as needed:
- *Italic*
- **Bold**
- ***Bold and Italic***
### Creating Lists
#### Unordered List
- Item 1
- Subitem 1.1
- Subitem 1.2
- Subsubitem 1.2.1
- Item 2
#### Ordered List
1. First item
2. Second item
1. Subitem 2.1
2. Subitem 2.2
1. Subsubitem 2.2.1
3. Third item
### Adding Links and Images
You can add [links](https://www.example.com) or insert images:

</textarea>
</div>
<div class="preview" id="preview">
<!-- Rendered HTML will appear here -->
</div>
</main>
<script>
// Enhanced Markdown Parser
function parseMarkdown(markdown) {
const lines = markdown.split('\n');
let html = '';
const listStack = []; // To handle nested lists
let inCodeBlock = false;
lines.forEach((line) => {
// Handle Code Blocks
if (line.trim().startsWith('```')) {
inCodeBlock = !inCodeBlock;
if (inCodeBlock) {
html += '<pre><code>';
} else {
html += '</code></pre>\n';
}
return;
}
if (inCodeBlock) {
html += escapeHTML(line) + '\n';
return;
}
// Handle Horizontal Rules
if (/^\s*---\s*$/.test(line)) {
closeAllLists();
html += '<hr />\n';
return;
}
// Handle Headings
const headingMatch = line.match(/^(#{1,6})\s+(.*)$/);
if (headingMatch) {
closeAllLists();
const level = headingMatch[1].length;
const content = processInline(headingMatch[2]);
html += `<h${level}>${content}</h${level}>\n`;
return;
}
// Handle Blockquotes
const blockquoteMatch = line.match(/^\s*>\s+(.*)$/);
if (blockquoteMatch) {
closeAllLists();
const content = processInline(blockquoteMatch[1]);
html += `<blockquote>${content}</blockquote>\n`;
return;
}
// Handle Lists
const listMatch = line.match(/^(\s*)([-*+]|\d+\.)\s+(.*)$/);
if (listMatch) {
const indent = listMatch[1].length;
const marker = listMatch[2];
const content = processInline(listMatch[3]);
const listType = /^\d+\./.test(marker) ? 'ol' : 'ul';
if (listStack.length === 0 || indent > listStack[listStack.length - 1].indent) {
// New nested list
html += `<${listType}>\n`;
listStack.push({ type: listType, indent });
} else {
// Close lists if necessary
while (listStack.length > 0 && indent < listStack[listStack.length - 1].indent) {
const lastList = listStack.pop();
html += `</${lastList.type}>\n`;
}
// If changing list type at the same level
if (listStack.length > 0 && listType !== listStack[listStack.length - 1].type) {
const lastList = listStack.pop();
html += `</${lastList.type}>\n<${listType}>\n`;
listStack.push({ type: listType, indent });
}
}
html += `<li>${content}</li>\n`;
return;
} else {
// Not a list item, close any open lists
closeAllLists();
}
// Handle Paragraphs
if (line.trim() !== '') {
const content = processInline(line);
html += `<p>${content}</p>\n`;
} else {
// Empty line; add a line break or skip
html += '';
}
});
closeAllLists();
return html;
// Helper Functions
function escapeHTML(text) {
return text.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">");
}
function processInline(text) {
// Escape HTML
let result = escapeHTML(text);
// Images
result = result.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, '<img src="$2" alt="$1" title="$3" />');
// Inline Code
result = result.replace(/`([^`]+)`/g, '<code>$1</code>');
// Bold and Italic
result = result.replace(/\*\*\*(.*?)\*\*\*/g, '<strong><em>$1</em></strong>');
result = result.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
result = result.replace(/\*(.*?)\*/g, '<em>$1</em>');
// Links
result = result.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, '<a href="$2" target="_blank" title="$3">$1</a>');
return result;
}
function closeAllLists() {
while (listStack.length > 0) {
const lastList = listStack.pop();
html += `</${lastList.type}>\n`;
}
}
}
const textarea = document.getElementById('markdown');
const preview = document.getElementById('preview');
function updatePreview() {
const markdownText = textarea.value;
const html = parseMarkdown(markdownText);
preview.innerHTML = html;
}
// Initial render
updatePreview();
// Event listener for real-time preview
textarea.addEventListener('input', updatePreview);
</script>
</body>
</html>
Detailed Explanation of Changes
-
Added Image Handling in processInline:
// Images
result = result.replace(/!\[([^\]]*)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, '<img src="$2" alt="$1" title="$3" />');
-
Regex Breakdown:
!\[([^\]]*)\]: Matches the alt text inside ![...].
\(([^)\s]+): Matches the image URL. This ensures there's no space in the URL for simplicity.
(?:\s+"([^"]+)")?: Optionally matches the title in quotes, e.g., .
-
Replacement:
- Converts the matched Markdown image syntax into an
<img> tag with src, alt, and optional title attributes.
-
Adjusted Link Handling:
Updated the link regex to also optionally capture the title attribute, ensuring that both links and images with titles are handled correctly.
// Links
result = result.replace(/\[([^\]]+)\]\(([^)\s]+)(?:\s+"([^"]+)")?\)/g, '<a href="$2" target="_blank" title="$3">$1</a>');
-
Optional CSS for Images:
Added styling to ensure that images fit well within the preview pane.
.preview img {
max-width: 100%;
height: auto;
display: block;
margin: 1em 0;
border-radius: 4px;
}
- Attributes Explained:
max-width: 100%: Ensures images don't exceed the width of their container.
height: auto: Maintains the aspect ratio.
display: block and margin: Adds spacing around images.
border-radius: Adds slight rounding to image corners for aesthetics.
-
Enhanced Regex for Better URL Matching:
The original regex might fail if the URL contains spaces or other complex characters. For a more robust solution, consider using a more comprehensive regex or a Markdown parsing library like marked.js or markdown-it which handle edge cases more effectively.
Testing Your Implementation
After making these changes:
-
Save the Updated HTML File: Ensure that your HTML file reflects the modifications above.
-
Open in Browser: Launch the HTML file in your preferred web browser.
-
Test Image Rendering:
-
Check Responsiveness:
- Resize the browser window to ensure that images scale appropriately within the preview pane.
-
Review for Bugs:
- Ensure that other Markdown features (like links, lists, headings) still work as expected.
- Check for any unintended side effects caused by the new image handling code.
Future Enhancements
While the above solution addresses image handling, consider the following for a more comprehensive Markdown editor:
-
Use a Reliable Markdown Parsing Library:
- Libraries like
marked.js or markdown-it are robust, well-maintained, and handle a wide range of Markdown features and edge cases.
- They also support extensions and plugins for additional functionality.
-
Implement Image Uploads:
- Allow users to upload images directly and host them using a service or local storage.
-
Enhance Security:
- Sanitize all user inputs more rigorously.
- Implement CSP headers to restrict the sources of images and other resources.
-
Support More Markdown Features:
- Tables, footnotes, task lists, etc., can enhance the editor's capabilities.
-
Improve Styling and UX:
- Add theme toggling (light/dark modes).
- Implement syntax highlighting within the editor for a better writing experience.
By incorporating these changes, your Dracula Markdown Editor will effectively handle image rendering, enhancing its functionality and user experience.