Je pense que je pourrais bien améliorer cela, mais à la minute c'est le meilleur que je peux offrir (même si je pense que certains types de remplacer pourrait fonctionner plus efficacement):
var $words = $('p').text().split(' ');
for (i in $words) {
if ($words[i].indexOf('http://') == 0) {
$words[i] = '<a href="' + $words[i] + '">' + $words[i] + '</a>';
}
}
$('p').html($words.join(' '));
JS Fiddle demo.
Une version légèrement améliorée de ce qui précède (mais bon seigneur, il est laid ...):
var punctuation = ['!',"'",'"',',','.'];
$('p').each(
function(){
$words = $(this).text().split(' ');
for (i in $words){
if ($.inArray($words[i].charAt(0),punctuation) > -1 && $words[i].indexOf('http://') == 1){
alert($words[i]);
}
else if ($.inArray($words[i].charAt($words[i].length - 1),punctuation) > -1 && ($words[i].indexOf('http://') == 1 || $words[i].indexOf('http://') == 0)){
$words[i] = '<a href="'+$words[i].substring(0,$words[i].length-1)+'">' + $words[i].substring(0,$words[i].length-1) + '</a>' + $words[i].charAt($words[i].length-1);
}
else if ($words[i].indexOf('http://') == 0){
$words[i] = '<a href="' + $words[i] + '">' + $words[i] + '</a>';
}
}
$(this).html($words.join(' '));
});
JS Fiddle demo.
Je ne suis pas très sûr de ce qu'il faut faire à propos des liens entre guillemets, par exemple (texte tel que "http://google.com"
, par exemple); et, honnêtement, je pense que regex est probablement le loin, loin meilleure approche à ce problème.
double possible de [ Comment remplacer les URL simples avec des liens?] (Http://stackoverflow.com/questions/37684/how-to-replace-plain-urls-with-links) – Eric