I suspect that I could much improve upon this, though at the minute this is the best I can offer (albeit I think that some kind of replace might work more efficiently):
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.
A slightly improved version of the above (but good lord, it's ugly...):
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.
I'm not quite sure what to do about quoted links, though (text such as "http://google.com"
, for example); and, honestly, I think that regex is probably the far, far better approach to this problem.