Js中經常遇到判斷一個字符串是否包含一個子串,java語言中有containes的方法,直接調用就可以了。除非引用第三方數據庫,Js中沒有contains方法。
為了實現更java語言中containes方法相同的效果,最簡單的一種做法是利用js中字符串查找位置的方法indexOf(“o”大寫)。此方法的返回的值得可能有 -1,0,n(正整數)三種情況。0是當子串在字符串第1位開始包含的情況下返回,例子如下:
<script> var str="he"; var string = "hello"; console.log(string.indexOf(str));//0 </script>
contains的方法:
<script> var str="he"; var string="hello"; function contains(subs,str){ return str.indexOf(subs)>=0?true:false; } console.log(contains(str,string));//ture </script>