1

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?

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

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.