Editors, chat apps and comment boxes rarely store formatting as HTML. They store the plain text and a list of style ranges: "bold from 0 to 5, italic from 3 to 11". Ranges can overlap freely, which tags cannot: <b>Hel<i>lo</b> world</i> is broken HTML. Turning ranges into HTML means cutting the text into pieces where the styles change, and nesting the tags so they never cross.
functionapplyStyles(text, ranges) // returns a string of HTML
text: the plain text.
ranges: an array of { start, end, style }. start is included and end is not, as in slice(start, end). style is one of "bold", "italic", "underline", "strike" and "code", written as <b>, <i>, <u>, <s> and <code>.
Each character is inside exactly the tags of the styles whose ranges cover it, and inside no other tag.
Tags always nest in one fixed order, outermost first: b, i, u, s, code. The order of ranges does not matter.
The HTML is minimal in this sense: a tag that the next piece of text also needs stays open. Neighbouring ranges of one style, and duplicate ranges, give a single tag. A tag is closed and reopened only when the fixed order forces it.
Tags are always balanced and never cross, and every tag is closed at the end.
The text is escaped: & to &, < to <, > to >, " to ", ' to '.
Ranges are clipped to the text. A range that is empty or reversed after clipping is ignored.
A style that is not one of the five throws a TypeError, including names such as "toString".
applyStyles("abcdefgh", [ { start: 2, end: 4, style: "italic" }, { start: 0, end: 8, style: "bold" },]);// "<b>ab<i>cd</i>efgh</b>": bold stays open around the italic part
JAVASCRIPT
applyStyles("abc", [ { start: 0, end: 3, style: "italic" }, { start: 1, end: 2, style: "bold" },]);// "<i>a</i><b><i>b</i></b><i>c</i>": b must be outside i, so the italic tag closes and reopens