2009-08-22 77 views
0

我已经有了一个项目,我必须确定一个字符串是否包含设置的字符串。 例子: 我在找什么“website.com” 什么是可能看起来像“jsngsowebsite.comadfjubj”使用Javascript检查字符串内容

到目前为止,我自己endevours已经取得了这一点:

titletxt = document.getElementById('title'); 
titlecheck=titletxt.IndexOf("website.com"); 

if (titlecheck>=0) 
{ 
    return false; 
} 

不似乎在做伎俩,有什么建议吗?

回答

1

Javascript函数是区分大小写 - indexOfIndexOf

4
function text(el) { 
    return el.innerText ? el.innerText : el.textContent; 
} 

function contains(substring, string) { 
    return string.indexOf(substring)>=0 
} 

contains('suggestions', text(document.getElementsByTagName('body')[0])) 

替换 '建议' 和document.getElements ......一个字符串和DOM元素引用。

titlecheck=titletxt.IndexOf("website.com"); 

这看起来就像你试图用一个DOM元素上的IndexOf(小写I)这甚至不会有这种方法,该文本是的textContent(标准DOM属性)或的innerText(内部IE特定属性)。

+0

包含函数应该> = 0 - 但否则+1用于指出DOM元素的innerText – gnarf 2009-08-22 22:02:53

+0

谢谢 - 滑倒了我的想法,尽管innerText是IE DOM特定的。 – 2009-08-22 22:06:29

0

您也可以使用String.match(...),如果没有找到匹配

title = document.getElementById('title'); 
titletxt = title.innerText ? title.innerText : title.textContent 
titlecheck = titletxt.match("website.com"); 

if (titlecheck != null) { 
    return false; 
} 

String.match返回null,并返回搜索字符串( “website.com”)如果比赛发现

1

可以使用indexOf()方法:

标题= “lalalawebsite.comkkk”;

// indexOf在'title'中找不到字符串'website.com'返回-1 titlecheck = title.indexOf(“website.com”)> 0? “找到”:“找不到”;

alert(titlecheck);