-3

Currently I use this:

function parseFormat(text) {
  text = text.replace(/[\_]{2}([^\_]+)[\_]{2}/g, '<u>$1</u>');
  text = text.replace(/[\*\_]{2}([^\*\_]+)[\*\_]{2}/g, '<b>$1</b>');
  text = text.replace(/[\*\_]{1}([^\*\_]+)[\*\_]{1}/g, '<i>$1</i>');
  text = text.replace(/[\~]{2}([^\~]+)[\~]{2}/g, '<del>$1</del>');
  return text;
}

And to parse: agent_messages.forEach(e => e.innerHTML = parseFormat(e.innerHTML));

And I wish to use other kind of combinations for above.

Like:

  • !@# for bold
  • $%^ for underline
  • &*( for italic
  • )_+ for strikethrough

So for bold it should be : !@# bold !@# (= bold)

Can anyone help with this code? It's quite complex.

Ronnie Oosting
  • 1,252
  • 2
  • 14
  • 35

1 Answers1

0

One problem with your approach is (using your "new" delimiters) what happens when you get this input?

normal !@# bold &*( bold-italic !@# italic &*( normal

This would be your output:

normal <b> bold <i> bold-italic </b> italic </i> normal

And that is not valid HTML due to the crossed tags.

Instead, you need some kind of parser. A very basic one would seek out a single valid tag, and then re-parse its contents recursively. For example:

const tags = {
  "!@#": "b",
  "$%^": "u",
  "&*(": "i",
  ")_+": "del"
};
const regexSanity = /[-[\]{}()*+?.,\\^$|#\s]/g; // https://stackoverflow.com/a/9310752/507674
const regex = new RegExp(
  "(" + Object.keys(tags).map(
    token => token.replace(regexSanity,'\\$&')
  ).join("|") + ")(.*?)\\1",
  "g");

const parse = input=>
  input.replace(
    regex,
    (_,tag,content) => `<${tags[tag]}>${parse(content)}</${tags[tag]}>`
  );

console.log(parse("normal !@# bold &*( bold-italic !@# italic &*( normal"));

Notice how, in this example, the italic isn't parsed, because its tag is crossed with the bold tag. This enforces correct nesting.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Hi Niet, your script works super-b! Thanks a lot for providing the answer which works :). I don't get it why people devote my question and your answer. But it doesn't matter. I had a complex question, and you just solved it perfectly. It looks very dynamic! I love it. – Ronnie Oosting Aug 12 '20 at 09:05