[英]Split a image tag on html string
code: 码:
<div id="start">
<p>"hi split html string"<p><br>"now"
<img class="image1" src="some src" master_src="some src" master_w="400" master_h="320">
"second tag is coming"<br><img class="image2" src="some src" master_src="some src" master_w="400" master_h="320"><h1>end here</h1>
</div>
output: 输出:
<p>"hi split html string"<p><br>"now" , "second tag is coming"<br> , <h1>end here</h1>
How can i achieve this ouput? 我如何实现此输出? what could be regex expression fot this image class in order to use split function(or any better way)?Please give me a demo
为了使用拆分功能(或任何更好的方法),此图像类的正则表达式可能是什么?请给我演示
I'm not completely sure I understand your end goal, but if you want to remove the image from the HTML, you can use the DOM. 我不能完全确定我是否了解您的最终目标,但是如果您想从HTML中删除图像,则可以使用DOM。 First create a dummy element and set its
innerHTML
to the HTML string: 首先创建一个虚拟元素,并将其
innerHTML
设置为HTML字符串:
var dummy = document.createElement('div')
dummy.innerHTML = html
Now you got a div that contains your HTML structure as DOM elements . 现在您有了一个div,其中包含HTML结构作为DOM元素 。 But, what you want is your div, not the dummy one:
但是,您想要的是div,而不是虚拟的div:
var div = dummy.children[0]
Then loop the children, check if it's an image and remove it if so: 然后循环孩子,检查是否是图像,如果是,则将其删除:
for (var i=0; i<div.children.length; i++) {
var child = div.children[i]
if (child.tagName == 'IMG') {
div.removeChild(child)
}
}
You can append the div to the DOM: 您可以将div附加到DOM:
document.body.appendChild(div)
Or you can get back the HTML as a string and without the images: 或者,您可以将HTML作为字符串而不包含图像来获取:
div.innerHTML
//^ <p>"hi split html string"</p><br>"now""second tag is coming"<br><h1>end here</h1>
Also note that your HTML is not valid, you didn't close the paragraph with </p>
, and so the above won't work if it isn't valid. 另请注意,您的HTML无效,没有使用
</p>
关闭该段落,因此如果无效,则以上内容将无效。
why are you askying the same question multiple time? 为什么多次问同一个问题?
Here is you answer 这是你的答案
$('#start').find('img').each(function(index){
var split_text = $(this).html().split(/<img[^>]*>/)[index];
alert(split_text)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.