0

So i read this question and i want to use its answer, however as overwrites everything i put in, if I for example add a red div it vanish. How can i make this javascript work well with my other html...

var newHTML = replaceWithImgLinks($(document.body).text());
$(document.body).html(newHTML);
function replaceWithImgLinks(txt) {
var linkRegex = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))/gi;
var replacement = '<a href="$1" target="_blank"><img class="sml" src="$1" /></a><br />'
return txt.replace(linkRegex, replacement);
}

(Im stupid and my javascript knowledge is not the best) if you could explain why it doesn't work aswell i would be very satisfied.:)

Here is a fiddle aswell so you can see my problem:

So what I am trying to do is so all the imgs srcs in my div is changed to images "instead of the whole body i think"

Community
  • 1
  • 1
Furious Mountain
  • 1,323
  • 3
  • 16
  • 44

1 Answers1

1

If you don't need the parameters of the URL, you can use \S* at the end of the regex.

/([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))\S*/gi

Also, I've changed the classes that you call & replace within JQuery:

function replaceWithImgLinks(txt) {
    var linkRegex = /([-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?(?:jpg|jpeg|gif|png))\S*/gi;
    return txt.replace(linkRegex, '<a href="$1" target="_blank"><img class="sml" src="$1" /></a><br />');
}

var newHTML = replaceWithImgLinks($('.chatMessages').html());
$('.chatMessages').html(newHTML);
.chatMessages{
  height:200px;
  width:200px;
  background-color:red;
}
.sml{
  height:100px;
  width:100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class = "chatMessages">
https://i.stack.imgur.com/qgNyF.png?s=328&g=1
</div>
Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
  • oh thanks alot, i tried to set document.(.chatMessages) before but it didn't work but i guess you only need to set .chatMessages instead of document body, and thanks aswell for helping me with my "next" problem with the parameters! – Furious Mountain Mar 08 '17 at 15:23
  • is there another way to remove parameters than \S* because it messes up my php of some reason? – Furious Mountain Mar 08 '17 at 19:47