2

Hi i have the following text in a div:

[http://www.google.com Google this link] some other random text [http://example.com and another website] but don't parse [this is not a link, leave me alone].

What I tried to do was to convert the links into normal html links. The Format is always like this, so it opens with a [ and then the url, followed by the link text and then a closing ]. But I only want to match links, not all text in square brackets.

I want to use the .match() function in javascript to do this task, but I wasn't able to figure out the regex expression (I only need the text parts that are links - the rest should be a simple split).

Any help would be apprechiated.

1
  • 1 - What have you tried? 2 - First, you say you only want to match the links, then you say you only need the text parts... Which is it? Commented Apr 22, 2013 at 10:07

1 Answer 1

5

Why .match and not .replace?

string.replace(/\[(https?:\/\/[^\]\s]+)(?: ([^\]]*))?\]/g, "<a href='$1'>$2</a>");
Sign up to request clarification or add additional context in comments.

2 Comments

wow... perfect. Someday, I need to get the hang of this... thank you!!
@mffap Yes, regexes are somewhat difficult but can do a great job. If the answer was useful, you can accept it by clicking on the tick mark on the left.

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.