2011-12-01 1 views
1

Pour l'instant, je le regex suivant pour le remplacement d'une URL à un lien hypertexte HTML:Regex pour l'URL de lien hypertexte

msg = msg.replace(/(\b((https?|ftp|file):\/\/|www.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi, "<a href='out.php?u=$1'>$1</a>"); 

Cette remplace

http://www.stackoverflow.com 

dans

<a href='out.php?u=http://www.stackoverflow.com'>http://www.stackoverflow.com</a> 

Mais maintenant j'ai un problème. Lorsque j'ai déjà un lien hypertexte, je ne veux pas remplacer l'URL de ce lien hypertexte par un nouveau lien hypertexte.

Alors:

<a href='http://www.stackoverflow.com'>Stackoverflow</a> 

ne doit pas devenir:

<a href='<a href='out.php?u=http://www.stackoverflow.com'>http://www.stackoverflow.com</a>'>Stackoverflow</a> 

Est-ce que quelqu'un sait comment je peux empêcher cela?

+0

Je pense que cela a déjà été répondu: http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links –

Répondre

1

je l'ai déjà fixé en ajoutant un espace blanc avant et après la chaîne, et remplace toutes les URL avec un espace avant et après:

msg = " " + msg + " "; 
msg = msg.replace(/(\s)(((https?|ftp|file):\/\/|www.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])(\s)/gi, " <a target='_blank' href=\"" + websiteUrl + "/out.php?u=$2\"><font color='" + hyperlinkColor + "'>$2</font></a> "); 
msg = StringUtil.trim(msg); 

Cela ne remplacez tous les liens hypertexte, car un lien hypertexte n'a pas d'espaces avant et après l'URL.

1

Vous pouvez le faire avec un assertion négative, écrite sous la forme (?! Expression). Alors ...

?!(\<a)/(\b((https?|ftp|file):\/\/|www.)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi, "<a href='out.php?u=$1'>$1</a>");