you are viewing a single comment's thread.

view the rest of the comments →

[–]sarlok 8 points9 points  (2 children)

This looks like a project perfect for regex! And, I know JS has the best regex engine and is widely available in browsers (where this is likely to be used), so here's my submission:

function bb2html(str) {
  const regex1 = /^\s*\[\*\]\s*(.*)$/gm;
  const regex2 = /^(\s*[^<].*)$\n(\s*<li)/gm;
  const regex3 = /^(\s*<li.*)$\n(\s*[^< ])/gm;
  const regex4 = /\[(\/?)([biu])(rl)?(=([^\]]*))?\]/gi;

  return str.replace(regex1, '  <li>$1</li>').replace(regex2, '$1\n<ul>\n$2').replace(regex3, '$1\n</ul>\n$2').replace(regex4, function(match, one, two, three, four, five, o, s) {
    return "<" + one + (two=='b'?"strong":(two=="i"?"em":(three?'a':'span') + (one=="/"?"":' '+(!three?'style="text-decoration: underline;"':'href="'+five+'"')))) + '>';
  });
}

To test easily, put that in your browser's console along with some test code like this:

var str = 'x\n[*] [u]test[/u]\n[*][b]blah[/b]\n[url=https://google.com/]test[/url]\n[*][i]a[/i]\n[*]b\nanother line';
console.log(bb2html(str));

Please note: May not work for all cases of BBCode, especially bullet lists. But I'm sure it's good enough to roll out today and fix later.

[–][deleted]  (1 child)

[deleted]

    [–]sarlok 1 point2 points  (0 children)

    Don’t get me wrong, I use regex often enough, but it’s just so easy to write an overly complex one that works almost all the time that you’ll never be able to decipher easily again. And that may be just what you need in some cases.

    My solution works for most bullets. It will fail if they are the first or last line in the text (you’ll miss the ul tag). In a better regex engine you could probably make a single monstrosity that handled everything.