JavaScript无法通过innerHTML搜索

问题描述:

我试图找到许多不同的文本类型在innerhtml中,不知何故,当我用相同的函数和测试样本测试它时,它找不到任何东西。JavaScript无法通过innerHTML搜索

function numberoftext (a){if (a.match(/class=\"chattext\"/g)!==null){return a.match(/class=\"chattext\"/g).length;}else{return 0;}} 
function numberofglobal (a){if (a.match(/class=\"chattextglobal\"/g)!==null){return a.match(/class=\"chattextglobal\"/g).length;}else{return 0;}} 
function numberofclan (a){if (a.match(/class=\"chattextclan\"/g)!==null){return a.match(/class=\"chattextclan\"/g).length;}else{return 0;}} 
function numberofgroup (a){if (a.match(/class=\"chattextgroup\"/g)!==null){return a.match(/class=\"chattextgroup\"/g).length;}else{return 0;}} 
function numberofwisper (a){if (a.match(/class=\"chattextwhisper\"/g)!==null){return a.match(/class=\"chattextwhisper\"/g).length;}else{return 0;}} 
function numberofworld (a){if (a.match(/class=\"worldsay\"/g)!==null){return a.match(/class=\"worldsay\">/g).length;}else{return 0;}} 
function numberofscream (a){if (a.match(/class=\"chattextscream\"/g)!==null){return a.match(/class=\"chattextscream\"/g).length;}else{return 0;}} 
var innertextraw1 =chatupdateFrame.document.documentElement.innerHTML; 
var innertextraw= innertextraw1.substring(innertextraw1.indexOf("parent.chattextFrame.add(")+26, innertextraw1.indexOf("', 0);")); 

console.log("got update",innertextraw); 
console.log("t:",numberoftext(innertextraw),"c:",numberofclan(innertextraw),"w:",numberofwisper(innertextraw),"gr:",numberofgroup(innertextraw),"gl:",numberofglobal(innertextraw),"sc:",numberofscream(innertextraw)); 

的innertextraw一个例子是:"<p class=\"chattext\"><i><b>noone</b> goes with <b>someone</b> to the house</i></p>" 还当我设置innertextraw到这是我从控制台日志得到了例如测试它像that正常工作,在网站上则返回0只是

你不需要转义您的"引号以匹配字符串中的转义引号。

a.match(/class="chattext"/g) 

在实际的字符串,这些逃生斜线实际上不存在的,但只是没有办法来表示文字双(或单)引号如果字符串使用的字符作为分隔符,所以你必须逃避它。

这里有一个工作示例:

var innerRawText = "<p class=\"chattext\"><i><b>noone</b> goes with <b>someone</b> to the house</i></p>"; 
 

 
var result = innerRawText.match(/class="chattext"/g); 
 
console.log(result);