我在正则表达式中遇到了一些麻烦。使用.match和正则表达式不起作用获取特定单词
我想匹配句子中的正则表达式。
例子:
John has two candy ::123::
,我使用此代码来寻找它:
var getid = x$('div').html().match(/::([^:]+)::/g);
要获得123句我们。
那么我的问题在这里? 我一直在为getid var获取未定义的值。
我在正则表达式中遇到了一些麻烦。使用.match和正则表达式不起作用获取特定单词
我想匹配句子中的正则表达式。
例子:
John has two candy ::123::
,我使用此代码来寻找它:
var getid = x$('div').html().match(/::([^:]+)::/g);
要获得123句我们。
那么我的问题在这里? 我一直在为getid var获取未定义的值。
问题是g
标志。您不要将它与String#match
一起使用。删除它,它工作正常(live copy | source):
var getid = x$('div').html().match(/::([^:]+)::/);
if (getid) {
display("Found: " + getid[1]);
}
else {
display("Not found");
}
如果你想找到所有匹配的文本,使用RegExp#exec
和环(和g
标志)(live copy | source):
var rex = /::([^:]+)::/g;
var str = x$('div').html();
var getid;
while (getid = rex.exec(str)) {
display("Found: " + getid[1]);
}
(为了更清楚,你可以使用
while ((getid = rex.exec(str)) != null) {
...因为在TE具有分配st看起来像=
而不是==
错字;但它涉及到比其他可读性同样的事情。)
回复您的评论如下询问x$(this)
,它应该有任何区别。以上是返回使用的上述示例:x$(this)
:
是啊x $是别名。但它的价值不明确。 – sm21guy 2012-03-25 13:11:04
你在页面中只有div吗?通过id访问元素可能是一个好主意。 – 2012-03-25 13:12:10
我正在使用(this).html();因为它上面是div ID。点击功能。 – sm21guy 2012-03-25 13:13:56