Arbaaz Arbaaz - 20 days ago 6
Javascript Question

Unable to find if a string contains a substring?

I am trying to have sql's like clause like effect in javascript.

I am aware that similar question are already present on internet but the following approach is not working for me:



$(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>





I have set substring which is to be looked up in string as "lan", which should push "PLANNING & PROJE         00000000PG" into the array. But it does not.

Answer

I think that the problem is with the letter casing. Try this :

$(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.toLowerCase().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>

Comments