JSFiddle - React, Tailwind, and code Playground

by Prathameshsb

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Rich Text Editor Example</title>
  <style>
    /* Add your styles here */
    i {
      font-style: italic;
    }

    b {
      font-weight: bold;
    }

    u {
      text-decoration: underline;
    }
  </style>
</head>
<body>

<script>
  function renderRichText(text, styles) {
    let result = '';
    let lastIndex = 0;

    // Iterate through each style range
    styles.forEach(style => {
      const [start, end, tag] = style;

      // Add the plain text before the style
      result += text.substring(lastIndex, start);

      // Open the style tag
      result += `<${tag}>`;

      // Add the styled text
      result += text.substring(start, end + 1);

      // Close the style tag
      result += `</${tag}>`;

      // Update the last index
      lastIndex = end + 1;
    });

    // Add any remaining plain text after the last style
    result += text.substring(lastIndex);

    return result;
  }

  // Example usage
  const inputText = 'Hello, world';
  const styles = [[0, 2, 'i'], [4, 9, 'b'], [7, 10, 'u']];

  const outputHTML = renderRichText(inputText, styles);

  // Display the result
  document.body.innerHTML = outputHTML;
</script>

</body>
</html>