I’m rewriting an userscript and replacing the use of dojo with jQuery, but then I came upon something, I got lost. 🙁
This is the script with dojo, it worked fine:
dojo.query(".body").forEach(function(node, index, arr){
kmfa.check(node,index);
});
kmfa.check = function(node){ //check for links/images and replace some stuff
regex= /(https?:\/\/([-\wäöü\.]+)+(:\d+)?(\/([-=_\w\.\%\@\#\~;:,\(\)\/\+]*(\?[^<>\s]+)?)?)?)/gi;
node.innerHTML = node.innerHTML.replace( /<a[^>]+>([^<]+)<\/a>/gi, '$1' );
node.innerHTML = node.innerHTML.replace( /<wbr>/g, '' );
if (node.innerHTML.indexOf('.png') != -1 || node.innerHTML.indexOf('.gif') != -1 || node.innerHTML.indexOf('.jpg') != -1 || node.innerHTML.indexOf('.tif') != -1 || node.innerHTML.indexOf('.bmp') != -1){
node.innerHTML = node.innerHTML.replace( regex, '<img src="$1" class="imgLimit" ></br><a href="$1">$1</a>' );
}else{
node.innerHTML = node.innerHTML.replace( regex, '<a href="$1" target="_blank">$1</a>' );
}
}
Now how do I get this to work with jQuery?
All I got so far is:
$('#forum').each(function (ind){
$(this).text(kmsi.replaceURLWithHTMLLinks($(this).text() ) )
});
kmsi.replaceURLWithHTMLLinks = function(text) {
var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
return text.replace(exp,"<a href='$1'>$1</a>");
}
but that isn’t working at all.
(I figure there will be comments like ‘why change to jQuery when you have it working?’. to answer those beforehand: i just wanna learn jQuery!)
Any help is welcome, thanks!
There are a couple of things I can see that are wrong:
First:
#forumwill select for an element with id forum. as an ID should be unique there will be only one result and thus no real point in the.each.If you are trying ot iterate over all the children of this element then you can do:
Another thing, if you want to insert HTML code into a dom element, you should use the
.html()method rather than the.text()method you use:I didn’t go into the regex part.