Ethan McTague
Ethan McTague

Reputation: 2358

JavaScript parse bbcode url

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?

Upvotes: 2

Views: 2675

Answers (1)

Olegas
Olegas

Reputation: 10517

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>')     

Upvotes: 6

Related Questions