简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM