skip to Main Content

My goal is to split overlapping positions to use in HTML. For example I have this text:

One two three

I want to make the second and third words bold, and first two words italic. We got something like that:

[
  { "start": 4, "end": 13, "markup": "BOLD" }, 
  { "start": 0, "end": 7, "markup": "ITALIC" }
]

If we wish to apply the HTML markups positionally, we get this:

<bold>One <em>two</bold> three</em>

See the overlapping? <em> open tag is broken by closing tag </bold>. It should be like:

<bold>One <em>two</em></bold><em> three</em>

And positions:

[
  { "start": 4, "end": 7, "markup": "BOLD" }, 
  { "start": 7, "end": 13, "markup": "BOLD" }, 
  { "start": 0, "end": 7, "markup": "ITALIC" }
]

P.S. Don’t mind that original positions are changed after applying markups. I wrote a good solution.

I tried to implement some solutions, but it seems like a daunting task for me.

2

Answers


  1. You could use the Javascript DomParser API to fix automatically the html structure

    const res = (new DOMParser())
        .parseFromString(
            "<bold>One <em>two</bold> three</em>",
            "text/html"
        );
    console.log(res.body.innerHTML)
    Login or Signup to reply.
  2. Not sure if your requirements state you have to used html for styling but for web best practices, I would recommend giving each a css class and then using css to make them bold and italic, toggling the classes as needed.

    <strong> and <em> are more used to indicate to semantic meaning to screen readers.

    According to the HTML5 specification,

    • <strong> should be used to indicate important parts of text.
    • <b> should be used to indicate text that should be easy to find.
    • <em> should be used to indicate emphasis.
    • <i> should be used for anything else that may appear in italics but you wouldn’t want emphasized.

    Once you have the css classes created, then you would just need to update the html with the relevant css classes you wanted at that point in time.

    For instance,

    <bold>One <em>two</em></bold><em> three</em>
    

    could be

    <span class="bold">One</span> <span class="bold em">two</span> <span class="em">three</span>
    

    This would allow you to have as many different styles on each one as you wanted rather than worrying about how each reacts to the other elements around them.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search