Wrapping a text url with <a> tags via jquery find and replace
I pick up the tweets via getJSON and write them to google map infowindow with javascript. The problem is that these tweets come with text links, but without formatting (and there are no identifiers / classes / anything that can be narrowed down for searching and replacing). This is a code trick that I'm using right now to find the text, but I can't get it to wrap everything it finds in the <a> tags to display the links correctly:
function wrap( str ) { return '<a href="' + str + '">' + str + '<\/a>'; }; function replaceText() { var jthis = $(this); $("*").each(function () { if (jthis.children().length == 0) { jthis.text(jthis.text().replace(/\bhttp[^ ]+/i, wrap)); } }); } $(document).ready(replaceText); $("html").ajaxStop(replaceText); Am I missing something or does anyone know a better way to do this?
+4
1 answer
If I understand your problem correctly, this should work. not sure why you are repeating elements since regexp still scans all the text.
<html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script> <script> function wrap( str ) { return '<a href="' + str + '">' + str + '<\/a>'; }; function replaceText() { $(".tweet").each( function(){ $(this).html($(this).html().replace(/\bhttp[^ ]+/ig, wrap)); }) } $(document).ready(replaceText); </script> </head> <body> <div class="tweet"> test 1 http://example.com/path </div> <div class="tweet"> test 2 http://example.com/path </div> </body> </html> +3