i have spent a while researching this and cant find a solution, i am looking for a method to remove all html tags from a string and if img tags appear, then replace them with just the src attribute, sorry for little information. Thanks.
2 Answers
First do a regex replace, replacing this
<img.+?src="(.+?)".*?>
with this \1. That will replace the whole img tags with just the contents of the src attribute.
Then do the replacement for all the rest of the tags using this
<.+?>
and replace with nothing/blank.
I think something like this might be what you need:
var str = "<b>TEST</b> <p><img src='path.png' /> boom <span>sss</span></p>";
var text = $(str).find('img').replaceWith(function() {
return $(this).attr('src');
}).end().text();
alert(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
3 Comments
P Clegg
Thanks, this code does answer my question so I'll accept as answer, however it does not work in my code, I'll have to adjust this code to suit my needs.
P Clegg
Could you please update your answer so others may see: $("<div>" + str + "</div>").find('img').replaceWith(function() {
Jason L.
If you're looking for a code answer, you should ask for code not a regex.