Lodder
Lodder

Reputation: 19733

Javascript convert [url=] to html link

I'm currently trying to convert this:

[url=http://example.com] this is a link [/url]

to a standard html link:

<a href=http://example.com>this is a link</a>

So far, I can convert the url string to a link, however the [url=] [/url] still remains and I'm not sure how to filter it out.

message.replace(/(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1'>$1</a>")

How can I filter out the [url=] [/url] in the regex and also ensure this is a link (text defined by the user) also remains?

Upvotes: 1

Views: 958

Answers (2)

Jerry
Jerry

Reputation: 71538

You just need to add it to your replace regex:

message.replace(/\[url=(\b(https?):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\]/ig, "<a href='$1'>$1</a>")
                 ^^^^^^

Though you still have the last url tag and you can make things easier with negated classes:

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

regex101 demo

EDIT: Made the closing tag a literal because of potential other tags

Upvotes: 5

mavrosxristoforos
mavrosxristoforos

Reputation: 3643

I would do that in 3 steps:

  • Replace [url= with <a href="
  • Replace [/url] with </a>
  • Replace ] with ">

But that's just an opinion. I usually like to keep it simple, and move on to the next problem.

Upvotes: 0

Related Questions