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 Commented 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]"
Sign up to request clarification or add additional context in comments.

3 Comments

Perfect, worked like a charm! Thanks for the explanation too!
@Hizan You could do even better doing this : .replace(/\[(.*?)\](?! *\[\/\1\])(.*?)\[\/\1\]/g, '<$1>$2</$1>'). Will match any BB tag :)
@Hizan I appreciate the comments. Sometimes askers don't give any feedback so, I feel like being blind, this is annoying :/ Keep enjoying :)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.