【发布时间】:2023-03-04 19:25:01
【问题描述】:
以下代码中的行为非常奇怪:
var showContent = document.getElementById("something"); // Search for a content
showContent = showContent.innerHTML;
var patt3=/Profile">[^<]*(?=<)/; // Search for this pattern ...
var showName=patt3.exec(showContent); // ... within the above found content
当我想在上述 showName 的结果中搜索一个字符串时,问题就开始了:
var yesTest = showName.indexOf("text");
alert(yesTest);
上面总是返回-1(没有找到内容)。然而,这
alert(showName);
显然其中确实有“文本”。我错过了什么吗?
【问题讨论】:
-
使用此模式:
/Profile">([^<]*)(?=<)/。然后,showName = patt3.exec(showContent);showName=showName ? showName[1] : '';showName.indexOf('text');。为什么?因为在您的情况下,indexOf不会从零开始,并且可能包括Profile。
标签: javascript regex search innerhtml indexof