Description

In rich-text editors, you often need to apply multiple styles to specific portions of a string. For example, applying bold, italic, or underline to different ranges of text.

In this challenge, you’ll build a parser function that converts a string and an array of style instructions into a properly styled HTML string.


Task

Implement a function parse(styleArr, str) that:

  • Takes a string str and a styleArr of [start, end, tag] instructions.
    • start: starting index of the style (inclusive)
    • end: ending index of the style (inclusive)
    • tag: HTML tag string ("b", "i", "u", etc.)
  • Wraps the specified ranges with the corresponding HTML tags.
  • Handles overlapping and nested styles correctly.
  • Returns a valid HTML string that can be rendered in the browser.

Method

Function

Description

parse(styleArr, str)

Returns a string with HTML tags applied according to styleArr.


Example

Input

const str = "Hello, world";
const styleArr = [
[0, 2, "i"], // italicize "Hel"
[4, 9, "b"], // bold "o, wor"
[7, 10, "u"], // underline "worl"
];

parse(styleArr, str);

Output

<i>Hel</i>l<b>o, <u>wor</u>l</b>d

Explanation

  • "Hel" → italicized
  • "o, wor" → bold
  • "worl" → underlined
  • Overlapping styles are nested properly.

Expected Behavior

✅ Supports multiple styles per range
✅ Handles overlapping and nested ranges
✅ Produces valid HTML
✅ Works with empty strings and empty style arrays


Hints

Hint 1

Use an array of characters from the original string to insert opening and closing tags.

Hint 2

Iterate over styleArr and insert <tag> at start and </tag> at end.

Hint 3

Use DOMParser (or other methods) to ensure valid HTML output.

Hint 4

Pay attention to nested or overlapping ranges — insertion order matters.