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.

souzan
  • 289
  • 1
  • 2
  • 14
Leonardo
  • 4,046
  • 5
  • 44
  • 85

1 Answers1

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>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875