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"

1 Answer 1

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.sstatic.net/qgNyF.png?s=328&g=1
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

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!
is there another way to remove parameters than \S* because it messes up my php of some reason?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.