views:

62

answers:

3

Hi

I am working on mail client application. I want to show all HTTP links as clickable hyper links.

I have noticed that some clients are sending HTTP links without enclosing them inside the anchor tags. In this case I am failing to show those links as clickable links.

My requirement is to find all HTTP links in a HTML mail and need to replace those links by enclosing them within anchor tags and also I need to exclude the links which are already in anchor tags or in source attribute of any tag.

Ex: Suppose my HTML mail is having the following text

Input:  "http://www.google.com/"     < a href = "http:\\gmail.com"></a>

After replacing I want the following out put

Output: <a href = "http://www.google.com"&gt; </a> < a href = "http:\\gmail.com"></a>

I think I can not directly look for pattern which starts with http... because it can also come as src of any tag.

So Can some one help me to solve these issue

Thanks in advance

Subbi

+2  A: 

I believe you can't do it properly in one regexp; and also, obligatory link. Why are you keen on doing it with regexp if you're working in JavaScript? Your interpreter is boxed together with the archetypal HTML parsing engine: a web browser. Just delve into DOM and replace on text nodes.

If you're not doing it in JS and the tag is just misleading, and you can't find a decent HTML parsing library, then your best bet is to split the string by tags, replace on non-tag elements, then join back up, I think.

Amadan
That link is awesome: "Even Jon Skeet cannot parse HTML using regular expressions." :D
FK82
A: 
Manoj
A: 

Hi,

I just tested this expression:

/\s+("http:[^\s]+")\s+/g 

This will replace every quoted URL enclosed by whitespace. You use it like this:

var string = "\"http://www.google.com/\"     < a href = \"http:\\gmail.com\"></a>" ; //!! the email string you provided
var replaced = string.replace(/\s+("http:[^\s]+")\s+/g," <a href=$1></a> ") ;

Other than that, javascript does not support (negative) lookbehind in regex which one would need to perfectly identify whether the matched URL was within a html tag or not.

HTH ,

FK

FK82