سؤال

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?

هل كانت مفيدة؟

المحلول

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>')     
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top