Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if a string contains a table

I have a question regarding checking the string.

The string is from a ckeditor so user can input anything.

The variable name is htmlData and it is like:

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 

I want to detect if user add a table structure and I have tried

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

but it doesn't show anything in my console. Can anyone gives a hint on this?

Thanks so much!

like image 721
FlyingCat Avatar asked Jul 29 '13 16:07

FlyingCat


2 Answers

String.indexOf() returns a primitive numeric value, specifically:

the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex or -1 if the value is not found.

These primitives have no properties, i.e.: length.

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

So, simply remove .length from your code:

if(htmlData.indexOf('</table>') > -1){
    console.log('table detected')
}
like image 66
canon Avatar answered Oct 14 '22 17:10

canon


You can use it:

if(/<table>/i.test(htmlData));
like image 43
Guerra Avatar answered Oct 14 '22 17:10

Guerra