2

I've been trying to make a simple bbcode parser, it works very well when the code is right but when there's no code I don't know how to handle it.

Here's my code:

function BBCodeHTML(text) {
    //WEBSITE 1
    code = '<iframe width="10" height="10" src="https://www.videoWebsite.com/video/$1"></iframe>';
    text = text.replace(/\[videoTag\](.*?)\[\/videoTag\]/g, code);
    return text;
    //WEBSITE 2
    code = '<iframe width="10" height="10" src="https://www.videoWebsite2.com/video/$1"></iframe>';
    text = text.replace(/\[videoTag2\](.*?)\[\/videoTag2\]/g, code);
    return text;
    [...]
}

The thing is, if the user just does [videoTag][/videoTag], the $1 thing (I don't know how to call it) is empty and the embed is still shown (without any video).

Is there anyway I can check if $1 is empty and IF IT IS NOT then replace with the embed?

Something like "if $1 = empty { do nothing } else { embed }"

I tried searching for answers but $1 empty etc gives me nothing.

If any mod knows a better title for this question, feel free to edit.

1
  • try (.+?) instead of (.*?), *-nothing or more, +-one or more
    – Grundy
    Feb 5, 2014 at 6:33

1 Answer 1

1

Try this regex :

var r = /\[tag\](?!\[\/tag\])(.*?)\[\/tag\]/g;

Let's say whitespaces are considered "empty" :

var r = /\[tag\](?! *\[\/tag\])(.*?)\[\/tag\]/g;

Usage example :

'[tag]  [/tag][/tag][tag]content[/tag]'.replace(r, '<tag>$1</tag>');
// "[tag]  [/tag][/tag]<tag>content</tag>"

The regular expression :

\[tag\]           "[tag]"
(?! *\[\/tag\])   not followed by zero or more whitespaces and "[/tag]"
(.*?)             any char, zero or more times
\[\/tag\]         "[/tag]"
3
  • Perfect, worked like a charm! Thanks for the explanation too!
    – Hizan
    Feb 5, 2014 at 6:48
  • @Hizan You could do even better doing this : .replace(/\[(.*?)\](?! *\[\/\1\])(.*?)\[\/\1\]/g, '<$1>$2</$1>'). Will match any BB tag :)
    – user1636522
    Feb 5, 2014 at 6:52
  • @Hizan I appreciate the comments. Sometimes askers don't give any feedback so, I feel like being blind, this is annoying :/ Keep enjoying :)
    – user1636522
    Feb 5, 2014 at 7:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.