在javascript中,查找字符串中的子字符串是否存在,我們可以只用indexOf方法來確定
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
<style>
body{
margin:0;
}
</style>
</head>
<body>
<script type="text/javascript">
var test="hello the fcuking world";
var subTest="world";
var result=test.indexOf(subTest);
if(result!=-1){alert("the subTest is contained");}
</script>
</html>
結果瀏覽器會彈出窗口內容“the subTest is contained
也就是檢測到字符串存在於test中
在這裏我們順便談論下 indexOf方法;
indexOf方法返回一個數字,用於表示子字符串的第一個字符串索引的位置,0表示第一個字符的位置,所以在上面我們需要檢測的是非負值,而檢查不到時會返回-1;
而indexOf方法可以接收兩個參數,第一個是我們要堅持的字符串,第二個則爲起始位置
如上test.indexOf(subTest,3); //這裏將表明從test字符串索引爲3的位置開始檢測,也就是hello 中的第二個l位置開始檢測,其返回值位置不變
lastIndexOf();逆向檢測,也就是從字符串最後位置往前檢測,返回值還是正序