2

I have been trying for a while to parse bbcode URL tags in JavaScript.

For example,

[url=http://examp.le]linktext[/url]

should become

<a href="http://examp.le">linktext</a>. 

I have done much research on this and have an awful understanding of regexes. So the question is, how can I do this?

3
  • If you have done much research on this, you should have at least something which works partly, right? Could you put that in your question? Commented Jan 4, 2014 at 18:27
  • I suggest you do not use regex for parsing BBCode as it's very difficult when you have multiple types of tags which may be used wrongly: [b]bold [u]underlined and bold[/b] wut[/u]. This should not be parsed like <strong>bold <u>underlined and bold</strong> wut</u> since that HTML isn't valid. Commented Jan 4, 2014 at 18:30
  • I only need to parse URL tags, but thank you for the advice. Commented Jan 4, 2014 at 19:04

1 Answer 1

6

You can try this regexp:

\[url=([^\s\]]+)\s*\](.*(?=\[\/url\]))\[\/url\]

Regular expression visualization

Debuggex Demo

So, in JavaScript you can use something like this:

text = text.replace(/\[url=([^\s\]]+)\s*\](.*(?=\[\/url\]))\[\/url\]/g, '<a href="$1">$2</a>')

jsFiddle demo

If you'd like to parse the short format

[url]http://ya.ru[/url]

which must transform to

<a href="http://ya.ru">http://ya.ru</a>

You'll need the following regexp:

\[url\](.*(?=\[\/url\]))\[\/url\]

Regular expression visualization

Debuggex Demo

And the corresponding JavaScript:

 text = text.replace(/\[url\](.*(?=\[\/url\]))\[\/url\]/g, '<a href="$1">$1</a>')     
Sign up to request clarification or add additional context in comments.

1 Comment

I wouldn't do it with regex. BB code needs a parser, since it is a markup with open/end tag similar to HTML.

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.