2012-08-29 53 views
-2

可能重複:
JavaScript: string contains搜索字符串

我要搜索的JavaScript字符串,看它是否含有某些字符

<script type="text/javascript"> 
var s="hello world"; 
if(s.contains("hello")) alert("contains"); 
</script> 

我可能期望像函數string.contains()。 是他們的一個string.contains在JavaScript或我應該使用indexOf而不是

+3

http://stackoverflow.com/questions/1789945/javascript-string-contains複製 – VirtualTroll

+1

這一直以前問過很多次,你應該在提問之前先搜索一下 – jbabey

回答

0

indexOf是要走的路 - 只是檢查返回值。

0

嘗試正則表達式:

if(/hello/.test(s)) 
    alert("contains"); 
0

如果你真的想要一個包含:

String.prototype.contains = function (searchTerm) { 
    return this.toString().indexOf(searchTerm) !== -1; 
}; 

如果你感覺花哨:

String.prototype.contains = function (searchTerm) { 
    return ~this.toString().indexOf(searchTerm); 
}; 
0
s.indexOf('hello') > -1 

(docs)

s.match('hello') === true 

docs,要知道,'hello'將在此情況下,可以解釋爲正則表達式。)