简体   繁体   中英

Replace an html element in a plain text string

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.

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 iframe s 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM