2

这可能是一个菜鸟问题,但我试图在这里和其他网站上找到答案,但我仍然没有找到答案。至少没有让我理解到足以解决问题。

这用于 chrome 的用户脚本。

我正在尝试从字符串中选择一个日期。该字符串是我设法选择的标签中的 innerHTML。html 结构以及字符串是这样的:(div 是选定的标签,因此其中的所有内容都是字符串的内容)

<div id="the_selected_tag">  
    <a href="http://www.something.com"  title="something xxx">link</a>  
    " 2011-02-18 23:02"  
    <a href="http://www.somthingelse.com" title="another link">thing</a>
</div>

如果您有一个解决方案可以帮助我选择没有这种模糊的日期,那也很棒。

的JavaScript:

var pattern = /\"\s[\d\s:-]*\"/i;
var tag = document.querySelector('div.the_selected_tag');
var date_str = tag.innerHTML.match(pattern)[0]

当我将此脚本用作 html 文档上的普通 javascript 来测试它时,它可以完美运行,但是当我将它作为用户脚本安装在 chrome 中时,它找不到模式。

我不知道如何解决这个问题。

4

2 回答 2

2

Dump innerHTML into console. If it looks fine then start building regexp from more generic (/\d+/) to more specific ones and output everything into a console. There is a bunch of different quote characters in different encodings, many different types of dashes.

[\d\s:-]* is not a very good choice because it would match " 1", " ". I would rather write something as specific as possible:

/" \d{4}-\d{2}-\d{2} \d{2}:\d{2}"/

(Also document.querySelector('div.the_selected_tag') would return null on your sample but you probably wanted to write class instead of id)

于 2011-02-18T23:36:41.933 回答
1

It's much more likely that tag.innerHTML doesn't contain what you think it contains.

于 2011-02-18T22:05:21.043 回答