我想在javascript中使用像sql這樣的子句。無法找到一個字符串是否包含子字符串?
據我所知,類似的問題已經存在互聯網上,但下面的方法是不是爲我工作:
$(document).ready(function() {
var listAll = [
"X1",
"ANTENNA SYSTEMS 00000000AS",
"Security & Wrokf 00000000CS",
"MICROWAVE & COMM 00000000MC",
"MICROWAVE SENSOR 00000000MT",
"PLANNING & PROJE 00000000PG",
"MECHANICAL SYSTE 00000000MS",
"ELECTRO-OPTICAL 00000000EO",
"SATCOM EXPERIMEN 00000000SE",
"QUALITY ASSURANC 00000000QA",
"QUALITY ASSURANC 00000000QC",
"DATA PRODUCTS SO 00000000DP"
];
var lstfiltered = ["X2"];
for (i = 0; i <= listAll.length - 1; i++) {
console.log(listAll[i]);
var string = listAll[i];
var substring = "lan";
if (string.indexOf(substring) !== -1) {
lstfiltered.push(string);
}
}
console.log(lstfiltered);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
我已經設置子是在字符串中查找作爲「lan」,應該將「PLANNING & PROJE 00000000PG」插入數組中。但事實並非如此。
區分大小寫?嘗試在比較之前先改爲小寫? – guradio
@guradio [是的](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf#Case-sensitivity)。 –
'toLowerCase()'使它不區分大小寫,或者你可以使用'localeCompare()'來比較字符串 –