How can I make a bbcode decoder that turns html end tags into the bbcode end tag they started as?

StackOverflow https://stackoverflow.com/questions/16908314

  •  30-05-2022
  •  | 
  •  

I have some javascript that will turn [b]test[/b] into <span class="bbcode_bold">test</span>

Also, this [i]test 2[/i] will turn into <span class="bbcode_italic">test</span>

That works fine, but I need to be able to decode that as well. With multiple types of bbcode that all have the same end tags, how can I figure a way to identify end tags as the bbcode tag they started as?

Edit: The code I use to parse text with bbcode in it:

function bbencode(input){
return input
.replace(/\n/ig, '<br/>')
.replace(/\[b\]/ig, '<span class="bbcode_bold">')
.replace(/\[\/b\]/ig, '</span>')
.replace(/\[i\]/ig, '<span class="bbcode_italic">')
.replace(/\[\/i\]/ig, '</span>')
;
}

My problem is in the decoder:

function bbdecode(input){
return input
.replace(/\n/ig, "<br/>")
.replace(/<span class="bbcode_bold">/ig, "[b]")
.replace(/<\/span>/ig, "[/b]")
.replace(/<span class="bbcode_italic">/ig, "[i]")
.replace(/<\/span>/ig, "[/i]")
;
}

Every span end tag needs to be interpreted as the bbcode end tag that it started as but there's no way to tell the difference. I tried putting classes in the end tags but firefox doesn't allow it.

有帮助吗?

解决方案

You could put a comment after the tag then test for that, e.g.:

function bbencode(input){
    return input
    .replace(/\n/ig, '<br/>')
    .replace(/\[b\]/ig, '<span class="bbcode_bold">')
    .replace(/\[\/b\]/ig, '</span><!--BOLD-->')
    .replace(/\[i\]/ig, '<span class="bbcode_italic">')
    .replace(/\[\/i\]/ig, '</span><!--ITALIC-->')
;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top