在两个图像之间获取文本 [英] get text between two images
问题描述
我正在为一个网页制作一个脚本。
赞:
< div id =content>< / div>
< div style =text-align:center>< img src =alt =>< / div>
< a>一些文字< / a>
< img src =alt =>
< div style =text-align:left>更多文字< / div>
< / div>
如何获取div内容的第一张图片和第二张图片之间的文字。我不知道完全正确的结构,因为可能文本和图像可能在div或节点内。我宁愿不使用库
您基本上要处理< img>
标签标记为要提取的文本周围的引号。
最简单的方法是替换< img> ;
标签,在文本中不可能重复,并将该字符用作分隔符。我会告诉你如何使用jQuery。如果你需要它在纯JS中完成比你不得不转换它。
首先制作一份HTML副本。
var html = $('< div>)。append($(#content)。html());
接下来,将所有< img>
html.find(img)。replaceWith( < DIV>〜< / DIV> 中);
一旦你完成了,你可以在这些分隔符之间匹配文本。
var str = html.text();
var rx = /〜([^〜] +)〜/ g;
var match = rx.exec(str);
要查找所有匹配项,请重复。 可以用一个独特的短语来做同样的事情,比如 这是一个可用的小提琴。 http://jsfiddle.net/thinkingmedia/etx1z6ov/2/ Is there a simpler way to catch the text between two images which haven't a same parent element?
I'm making a userscript for a webpage.
Like: How to get the text between the 1st image and 2nd image of the div content. I don't know exactly the correct structure because maybe the text and the images could be inside of div or a nodes. I'd rather not use libraries You basically want to handle the The easiest way to do that is to just replace the First, make a copy of the HTML. Next, replace all Once you've done that you can just match text between those delimiters like this. To find all matches just repeat. It's possible to do the same with a unique phrase like Here's a working fiddle. http://jsfiddle.net/thinkingmedia/etx1z6ov/2/ 这篇关于在两个图像之间获取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<$ (匹配!=空)
{
alert(match [1]); p $ p>
match = rx.exec(str);
$ / code> @img @
代替单个字符,但单个字符更容易。
<div id="content"></div>
<div style="text-align:center"><img src="" alt=""></div>
<a>some text</a>
<img src="" alt="">
<div style="text-align:left">more text</div>
</div>
<img>
tags as quotes around text you want to extract.<img>
tag with something not likely repeated in the text, and use that character as a delimiter. I'll show you how using jQuery. If you need it done in pure JS than you'll have to convert this. var html = $('<div>').append($("#content").html());
<img>
tags with a special character (or other token you know is unique).html.find("img").replaceWith("<div>~</div>");
var str = html.text();
var rx = /~([^~]+)~/g;
var match = rx.exec(str);
while(match != null)
{
alert(match[1]);
match = rx.exec(str);
}
@img@
instead of a single character, but a single character is way easier.