1

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 2

2

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.

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

2 Comments

Wouldn't <?.+> be greedy and therefore match the entire string <b>this is my text</b> rather than just <b> and </b>?
Yes, you are totally correct! I had a typo. It should have read <.+?>. Thanks for pointing that out. :)
1

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

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.
Could you please update your answer so others may see: $("<div>" + str + "</div>").find('img').replaceWith(function() {
If you're looking for a code answer, you should ask for code not a regex.

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.