0

I have a plain string:

var text = '<p>hello</p> <iframe src="http://whatever.com/1"></iframe><iframe src="http://notsosure.com"></iframe><iframe src="http://whatever.com/2"></iframe><p>goodby</p>'

I need to remove each iframe from the string starting with src=http://whatever.com and replace them with a link pointing to the same url.

I thought I could do something like this with jQuery:

$text = $(text)
$text
    .find("iframe[src^='http://whatever.com']")
    .replaceWith('<a href="' + $( this ).attr('src') + '"> Click Here</a>')

But this doesn't work as it return the replaced string and it doesn't modify my original $text object.

0

1 Answer 1

4

You're on the right track using an HTML parser, not naive text processing using a regular expression (obligatory link). Just a couple of things:

  • Your structure may have iframes at the top level, but find won't find them there.
  • You have to keep going: Turn it back into a string.

So for instance (see comments):

var text = '<p>hello</p> <iframe src="http://whatever.com/1"></iframe><iframe src="http://notsosure.com"></iframe><iframe src="http://whatever.com/2"></iframe><p>goodby</p>';
// Put them in a wrapper for convenience, so we don't have to worry about iframe
// elements at the top level
var wrapper = $("<div>");
wrapper.append(text);
// Find and replace the relevant iframe elements
wrapper.find("iframe[src^='http://whatever.com']").each(function() {
  $(this).replaceWith($("<a>").attr("href", this.src));
});
// Turn it back into text
text = wrapper.html();
console.log(text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Comments

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.