最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Remove the first img tag in a string of HTML using javascript and regex - Stack Overflow

programmeradmin1浏览0评论

Using Javascript and regular expression, given:

stringHTML = "bla bla bla <img src='img1.png' /> bla bla bla 
<img src='img2.png' /> bla bla bla <img src='img3.png' />";

How do you remove

<img src='img1.png' />

the first img tag from stringHTML

Using Javascript and regular expression, given:

stringHTML = "bla bla bla <img src='img1.png' /> bla bla bla 
<img src='img2.png' /> bla bla bla <img src='img3.png' />";

How do you remove

<img src='img1.png' />

the first img tag from stringHTML

Share Improve this question asked Sep 20, 2013 at 21:49 ardiwineardiwine 331 silver badge4 bronze badges 2
  • Obligatory – tckmn Commented Sep 20, 2013 at 21:50
  • 2 With String.replace(/<img[^>]+>/, ''). Without g flag, there'll be only a single replacement. – raina77ow Commented Sep 20, 2013 at 21:51
Add a ment  | 

2 Answers 2

Reset to default 4

Something like this would work:

var output = stringHTML.replace(/<img src='img1.png' \/>/, '');

This will find only the exact substring you've specified (a literal <img src='img1.png' />) and replace it with an empty string. Note that the forward slash needs to be escaped in the pattern because JavaScript uses forward slashes to delimit regular expression literals.

To remove the first <img> tag from the input string, regardless of the path or other attributes, you can use this:

var output = stringHTML.replace(/<img.*?\/>/, ''); 

This will find a literal <img followed by zero or more of any character, non-greedily, followed by a literal />. Note that without the global switch (g) it will only replace the first occurance

JavaScript es with wonderful DOM parsing capabilities build right in.

x = document.createElement("x");
x.innerHTML = stringHTML;

x.removeChild(x.querySelector("img"));

Note that querySelector("img") selects the first image. If you specifically need to select the image with src=img1.png you can use the attribute selector. If query selector is not available, you will have to loop over img tags acquired with getElementsByTagName.

http://jsfiddle/ZsqK5/

发布评论

评论列表(0)

  1. 暂无评论