DEV Community

Cover image for From Plain Text to Web Magic: Building a Text-to-HTML Converter with JavaScript and React
Random coder
Random coder

Posted on

From Plain Text to Web Magic: Building a Text-to-HTML Converter with JavaScript and React

In the world of web development, transforming plain text into structured HTML is a common necessity. Whether you're building a content management system, a forum, or any application that handles user-generated text, having a reliable text-to-HTML converter is crucial. Today, we'll explore how to build such a converter using JavaScript and React, and we'll also introduce you to a handy online tool that simplifies this process: Text to HTML Converter.

Why Text-to-HTML Conversion Matters

Plain text, while simple, lacks the formatting and structure required for web display. HTML, on the other hand, provides the necessary tags to define headings, paragraphs, lists, and more, ensuring your content is presented correctly in a browser.

Building a Basic Text-to-HTML Converter with JavaScript

Let's start with a simple JavaScript function that converts basic text into HTML paragraphs.

function textToHtml(text) {
  const lines = text.split('\n');
  const html = lines.map(line => `<p>${line}</p>`).join('');
  return html;
}

const plainText = "This is the first line.\nAnd this is the second line.";
const htmlOutput = textToHtml(plainText);
console.log(htmlOutput);
Enter fullscreen mode Exit fullscreen mode

This function splits the input text into lines and wraps each line in

tags. However, this is quite basic. To handle more complex formatting, we need to add more logic.

Enhancing the Converter with Regular Expressions

We can use regular expressions to detect and convert specific patterns, such as headings and lists.

function enhancedTextToHtml(text) {
  const lines = text.split('\n');
  let html = '';

  lines.forEach(line => {
    if (line.startsWith('# ')) {
      html += `<h1>${line.substring(2)}</h1>`;
    } else if (line.startsWith('* ')) {
      html += `<li>${line.substring(2)}</li>`;
    } else {
      html += `<p>${line}</p>`;
    }
  });

  if (html.includes("<li>")){
    let listItems = html.split("<li>");
    let listContent = "<ul><li>" + listItems.slice(1).join("<li>") + "</ul>";
    html = html.replace(new RegExp("<li>(.*?)</li>","g"),"");
    html = html.replace(new RegExp("</ul>","g"), listContent);
  }

  return html;
}

const enhancedText = "# Heading 1\n* List item 1\n* List item 2\nNormal paragraph.";
const enhancedHtml = enhancedTextToHtml(enhancedText);
console.log(enhancedHtml);
Enter fullscreen mode Exit fullscreen mode

This improved function handles headings (starting with #) and list items (starting with *).

Integrating with React

Now, let's incorporate this functionality into a React component.

import React, { useState } from 'react';

function TextToHtmlConverter() {
  const [inputText, setInputText] = useState('');
  const [htmlOutput, setHtmlOutput] = useState('');

  const handleInputChange = (event) => {
    setInputText(event.target.value);
  };

  const convertText = () => {
    setHtmlOutput(enhancedTextToHtml(inputText));
  };

  return (
    <div>
      <textarea value={inputText} onChange={handleInputChange} rows={10} cols={50} />
      <button onClick={convertText}>Convert to HTML</button>
      <div dangerouslySetInnerHTML={{ __html: htmlOutput }} />
    </div>
  );
}

export default TextToHtmlConverter;
Enter fullscreen mode Exit fullscreen mode

This React component provides a text area for input, a button to trigger the conversion, and a div to display the resulting HTML.

Introducing Randzy's Text-to-HTML Converter

While building your own converter is a great learning experience, sometimes you need a quick and reliable solution. That's where Randzy's Text to HTML Converter comes in.

Randzy's tool offers a user-friendly interface for converting text to HTML without writing any code. It supports various formatting options, including headings, lists, bold, italics, and more. Simply paste your text, and the tool will generate the corresponding HTML code.

Why Choose Randzy?

Ease of Use: No coding required.
Comprehensive Formatting: Supports a wide range of HTML elements.
Fast and Reliable: Get instant results.
Free and Accessible: Available online, anytime.
Conclusion

Building a text-to-HTML converter with JavaScript and React is a valuable skill for web developers. However, for quick and efficient conversions, Randzy's Text to HTML Converter offers a convenient solution. Whether you're a seasoned developer or just starting out, having the right tools at your disposal can significantly streamline your workflow.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)