Javascript 检测字符串是否包含表

Javascript 检测字符串是否包含表,javascript,jquery,html,ckeditor,Javascript,Jquery,Html,Ckeditor,我有一个关于检查字符串的问题 字符串来自ckeditor,因此用户可以输入任何内容 变量名称为htmlData,如下所示: test here<br /> <table border="1" cellpadding="1" cellspacing="1" style="width: 500px;"> <tbody> <tr> <td> 111</td&

我有一个关于检查
字符串的问题

字符串
来自
ckeditor
,因此用户可以输入任何内容

变量
名称为
htmlData
,如下所示:

test here<br />
<table border="1" cellpadding="1" cellspacing="1" style="width: 500px;">
    <tbody>
        <tr>
            <td>
                111</td>
            <td>
                222</td>
        </tr>
        <tr>
            <td>
                333</td>
            <td>
                444</td>
        </tr>
        <tr>
            <td>
                555</td>
            <td>
                666</td>
        </tr>
    </tbody>
</table>
<br />
second test 
但是它在我的
控制台中没有显示任何内容。有人能给点提示吗

非常感谢

字符串。
返回一个基本数值,具体如下:

指定值第一次出现的调用
字符串
对象中的
索引
,如果未找到该值,则从
索引
-1
开始搜索

这些原语没有属性,即:
length

if(htmlData.indexOf('</table>').length > -1){
    console.log('table detected')
}
使用-

为什么要这么长

if(htmlData.indexOf('</table>') > -1){
         console.log('table detected')
    }
if(htmlData.indexOf(“”)>-1){
console.log('检测到表')
}
这应该行得通。indexOf返回索引(-1),如果未找到,则不是数组,因此未定义长度属性

您可以使用它:

if(/<table>/i.test(htmlData));
if(//i.test(htmlData));

IndexOf没有属性
length
。正如名称“index”所示,它为您提供了索引。 此外:如果用户输入了结束标记,为什么只进行检查?您还应该检查开始标记。然后-为什么不使用正则表达式,如:

/<table>.*?<\/table>/.test(htmlData)
/.*./.test(htmlData)
两者都要测试吗


山洞!此正则表达式不检查用户是否输入了有效的html表标记。这只是一个愚蠢的检查resp.

将相同的答案添加到集合中是愚蠢的,因此,使用
match
这个方法怎么样,它将告诉您该字符串中有多少个表

var string = htmlData.replace(/\s/g, ""); 
// Trim all whitespace..

var matches = string.match(/<\/table>/g); 
// Will return 1 for your code and 2 for the demo

但是这并没有引用OP的字符串(htmlData)是的,你是对的Lee Taylor,我没有恰当地阅读这个问题你是否使用CAVE作为警告的缩写?我以前从没听说过。嗯。。我的拉丁语语法有点晦涩难懂。但据我记忆所及,这是一个类似于:cave canem!-小心点!。警告的意思类似:“你可能”或“你必须”或“某人必须”。不知道如何将我的拉丁语语法知识从德语翻译成英语;)我相信为了让你的第二个建议起作用,你需要将它包装在一个容器
var el=$(''+htmlData+'')中
您将得到一个
未捕获错误:语法错误,无法识别的表达式
正确,必须将其包装。但在Firebug中没有得到任何错误,需要查看它。同时修正答案。谢谢如果(~htmlData.indexOf(''){…}
var el = $(htmlData);
if(el.find(".some-class").length>0){
    console.log("it contains some-class");
}
if(htmlData.indexOf('</table>') > -1){
         console.log('table detected')
    }
if(/<table>/i.test(htmlData));
/<table>.*?<\/table>/.test(htmlData)
var string = htmlData.replace(/\s/g, ""); 
// Trim all whitespace..

var matches = string.match(/<\/table>/g); 
// Will return 1 for your code and 2 for the demo
if( matches > 0 ) {
  // There is at least 1 table here
}