2013-07-29 24 views
5

我有一個關於檢查string的問題。檢測字符串是否包含表格

string是從ckeditor,因此用戶可以輸入任何內容。

variable名字是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 

我想,如果用戶添加一個table結構來檢測和我都試過

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

,但它並不顯示任何東西我的console。任何人都可以提供一個提示嗎?

非常感謝!

回答

8

String. indexOf()返回原始數值,具體有:

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.

這些原語沒有的特性,即:length

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

所以,簡單地從你的代碼中刪除.length: -

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

,或者您可以使用找到任何標籤的jQuery -

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

神......我在想什麼....所有+1 – FlyingCat

+0

你可以把它更短'如果有( 〜htmlData.indexOf('')){...}' – oleq

3

使用

var el = $("<div>"+htmlData+"</div>"); 
if(el.find("table").length>0){ 
    console.log("it contains table"); 
} 

它將適用於任何標籤,類,ID或任何CSS選擇器。

var el = $(htmlData); 
if(el.find(".some-class").length>0){ 
    console.log("it contains some-class"); 
} 
+0

我相信爲了讓你的第二個建議工作,你需要將它包裝在一個容器中var el = $('

'+htmlData+'
');' –

+0

I認爲它會工作而不包裝它與'div'。 –

+0

你會得到一個'未捕獲的錯誤:語法錯誤,無法識別expression' http://jsfiddle.net/bplumb/CcxWV/ –

1

爲什麼.length?

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

這應該很好。 IndexOf返回的索引(-1)如果沒有找到,不是數組所以長度屬性沒有定義

3

可以使用它:

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

但這並不引用OP的字符串(htmlData) –

+0

呀,找你右李泰勒,我不恰當地閱讀問題 – Guerra

+0

OK,更新或刪除。謝謝 –

1

的IndexOf沒有屬性length。正如名稱「索引」所示,它會給你索引。 此外:如果用戶輸入了結束標籤,爲什麼只檢查?你也應該檢查開始標籤。然後 - 爲什麼不使用正則表達式:

/<table>.*?<\/table>/.test(htmlData) 

要測試兩者嗎?

CAVE!此RegEx未檢查用戶是否輸入了有效的html表格標記。這只是一個愚蠢的檢查發生<表> resp。 </table>

+0

您是否使用_CAVE_作爲_CAVEAT_的簡稱?我從來沒有聽說過。 – canon

+0

恩......我的拉丁文語法有點塵土飛揚。但據我記憶,這是一個如下的聲音:洞穴卡內姆! - 看狗!警告意味着類似的東西:「你可能」或「你必須」或「一個必須」。不知道如何將我的拉丁語法知識從德語翻譯成英語;) –

1

將同樣的答案添加到集合中是愚蠢的,那麼如何使用這個方法使用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 

然後你會檢查它像這樣

if(matches > 0) { 
    // There is at least 1 table here 
} 

Demo

相關問題