Parse URL's with jQuery

How can I use javascript, more importantly, jQuery to auto-parse any URL in my paragraph text to a clickable link?

I thought about trying to do this server side with PHP, but thought perhaps it would be faster using JavaScript, as I have a lot of stuff going on as it is.

Thanks in advance!

See if this works

var URLregex = new RegExp();
URLregex.compile("(^|[ \	\\r\
])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))","g");

$(document).ready(function(){
    $('p').replace(URLregex, ' <a href="$2" target="_blank">$2</a> ');
});

Hi. I couldn’t get this to work but it looks like it should!

I have tried this with some PHP code I found, but it destroyed an <embed><object> i had (which shouldn’t be in the paragraph, but it is, since it’s coming from MySQL) - so i had to disable it. :frowning:

Try this, I’ve tested it and it appears to be working fine

$('p').html($('p').html().replace(URLregex, ' <a href="$2" target="_blank">$2</a> '));

When I try that code, my paragraph text actually disappears. Weird.

maybe i should explain more. i got so much going on, on the server-side, i thought perhaps doing this clientside would be easier on the server. i guess i want to parse any sort of url on the page, but already i’ve ran into conflicts (like an embedded video that got destroyed by the code). Since that happened I stopped using the PHP function to parse the URLS. I’ve copied your code and pasted it in my <head> section. But when it loads the page, all my paragraphs are there, and then they disappear suddenly. So at the moment, I have commented out all url parsing functions to stop any further problems from occuring.

I really only need to parse url’s present in text from the database. Which is inside a <p> tag that is, more importantly, inside #content-wrapper.

So I guess the jQuery selector would be:

$(“#content-layout p”)

I can try and copy parts of the code, but I don’t see it doing any good, as I’ve copied exactly what you have here. I am using Google Chrome though, if that makes any difference but I think jQuery doesn’t have any issues with Chrome, so I dunno.

This is confusing to me. haha. I really do appreciate your help though. :slight_smile: Cheers

I’ve refined the code once more and it works correctly now, it shouldn’t conflict with the embed you have so try this

$(document).ready(function(){
    var pElements = $('#content-layout p');
    
    for(i=0, max=pElements.length; i<max; i++){
        $(pElements[i]).html($(pElements[i]).html().replace(URLregex, ' <a href="$2" target="_blank">$2</a> '));
    }
});

Ok, my <p> text shows up, but the links aren’t transformed. Here is my javascript file… I am totally clueless as to why this is happening!


$(document).ready(function(){

$("#delicious, #delicious-tagcloud").hide();

$("#uptime").countdown({ since: new Date(2010, 1, 1, 3, 48) });

$("#sidebar h3#hdr-delicious")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#delicious, #delicious-tagcloud").slideToggle("slow"); });
$("#sidebar h3#hdr-thefinalfrontier")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#thefinalfrontier").slideToggle("slow"); });
$("#sidebar h3#hdr-uptime")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#uptime").slideToggle("slow"); });
$("#sidebar h3#hdr-lastfm")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#lastfm").slideToggle("slow"); });
$("#sidebar h3#hdr-twitter")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#twitter-update").slideToggle("slow"); });
$("#sidebar h3#hdr-tags")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#tags-list").slideToggle("slow"); });
$("#sidebar h3#hdr-articles")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#articles-list").slideToggle("slow"); });
$("#sidebar h3#hdr-vintagegamers")
	.css({ "cursor" : "pointer" })
	.click(function() { $("#vg").slideToggle("slow"); });

var URLregex = new RegExp();
var pElements = $('#content-layout p');
URLregex.compile("(^|[ \	\\r\
])((ftp|http|https|gopher|mailto|news|nntp|telnet|wais|file|prospero|aim|webcal):(([A-Za-z0-9$_.+!*(),;/?:@&~=-])|%[A-Fa-f0-9]{2}){2,}(#([a-zA-Z0-9][a-zA-Z0-9$_.+!*(),;/?:@&~=%-]*))?([A-Za-z0-9$_+!*();/?:~-]))","g");


for( i = 0, max = pElements.length; i < max; i++ )
{
	$(pElements[i]).html($(pElements[i]).html().replace(URLregex, ' <a href="$2" target="_blank">$2</a> '));
}


// End
});

Is #content-layout attached to a div or the p element directly? If its attached to the p element remove the p from the jQuery anchor or wrap it in a div

go figure… i think it’s maybe the way i’ve designed my page that is screwing everything up. the “FULL” path from html for what i am trying to target is

html body div#layout-wrapper div#content-wrapper p.article-fulltext

as a side note to this, regex i posted in the php forum for <code></code> isn’t working either, so i am debating going through every db entry and adding <p> directly and removing my nl2br() function when i parse the data. this is irritating as everything i try is breaking.

I am posting the code that I want to target (this is PHP, so please forgive me on that). Perhaps you might be able to see a problem that the JavaScript is running into or something.


<?php
#begin =========================================================
$sql = $rsql['fetch_latest_news'];
$rs = mysql_query(safeQuery($sql), $db)
	or die(mysqlDebug('rs'));
if ( mysql_num_rows($rs) >= 1 ):
	$sql2 = $rsql['fetch_tags_by_article'];
	while ( ( $row = mysql_fetch_object($rs) ) == true ):
		$rs2 = mysql_query(safeQuery($sql2, $row->TextID), $db)
			or die(mysqlDebug('rs2'));
		if ( mysql_num_rows($rs2) >= 1 ):
			while ( ( $row2 = mysql_fetch_object($rs2) ) == true ):
				if ( $x == 1 ):
					$tag .= '<li class="second-item"><a href="';
				else:
					$tag .= '<li><a href="';
				endif;
				$tag .= makeURL('tags?name='.urlencode($row2->TagName));
				$tag .= '">';
				$tag .= $row2->TagName;
				$tag .= '</a></li>';
				$x++;
			endwhile;

			$fulltext = $row->TextFull;
			#$fulltext = preg_replace_callback('~((?:https?://|www\\d*\\.)\\S+[-\\w+&@#/%=\\~|])~', 'parse_links_v2', $fulltext);
			#$fulltext = preg_replace('~^.*(<code>.*</code>)\\s.*?~i', '<code>'.highlight_string($1).'</code>, $fulltext);
			$fulltext = ( strlen($fulltext) >= $truncate['latest_news'] ) ? nl2br(substr($fulltext, 0, ($truncate['latest_news']-1))) . '... <a href="'.makeURL('entry', 'id='.$row->TextID).'" class="disblock"><span class="rarr">&#0187;</span> Read More</a>' : nl2br($fulltext);
# break ========================================================
?>									
	<h3>
		<a href="<?php echo makeURL('entry', 'id='.$row->TextID); ?>">
			<?php echo $row->TextTitle; ?>
		</a>
	</h3>
	<h4>Word Count: <em><?php echo str_word_count($row->TextFull); ?> | <a href="#top">Top Of Page</a></h4>
	<p class="article-abstract hide">
		<?php echo $row->TextAbstract; ?>
	</p>
	<p class="article-fulltext">
		<?php echo $fulltext; ?>
	</p>
	<ul class="article-auth">
		<li class="label-tag">Posted on</li>
		<li class="second-item"><?php echo date_format(date_create($row->TextTimestamp, timezone_open("America/Indianapolis")), DATE_RFC850); ?></li>
	</ul>
	<ul class="article-auth">
		<li class="label-tag">Category:</li>
		<li class="second-item"><a href="<?php echo makeURL('category', 'id='.$row->CategoryID); ?>"><?php echo $row->CategoryName; ?></a></li>
	</ul>
	<ul class="article-auth">
		<li class="label-tag">Author:</li>
		<li class="second-item"><a href="<?php echo makeURL('user', 'id='.$row->UserID); ?>"><?php echo $row->Username; ?></a> <span class="rarr">&#0187;</span> <a href="<?php echo makeURL('user', 'id='.$row->UserID); ?>">View User Profile</a></li>
		<li><a href="<?php echo makeURL('entry', 'id='.$row->TextID); ?>">Permalink</a></li>
	</ul>
	<ul class="article-auth">
		<li class="label-tag">Options</li>
		<li class="second-item"><a href="#top">Top Of Page</a></li>
		<li><a href="#">Post Comment</a></li>
		<li><a href="#">View Comments (0)</a></li>
	</ul>
	<ul class="article-tags">
		<li class="label-tag">Filed Under</li>
		<?php echo $tag; ?>
	</ul>
	<hr />
<?php
# continue =====================================================
			$tag = null;
			$x = 1;
		endif;
	endwhile;
	mysql_free_result($rs);
	mysql_free_result($rs2);
else:
#break =========================================================
?>
	<h3>Whoops!</h3>
	<p>Sorry, but I cannot process your request at this time.</p>
<?php
#continue ======================================================
endif;
#break - final =================================================
?>