JavaScript filter an array of strings, matching case insensitive substring?


Let’s first create array of strings −

let studentDetails =
[
   {studentName: "John Smith"},
   {studentName: "john smith"},
   {studentName: "Carol Taylor"}
];

Now, match case insensitive substring, use the filter() and the concept of toLowerCase() in it. Following is the code −

Example

let studentDetails =
[
   {studentName: "John Smith"},
   {studentName: "john smith"},
   {studentName: "Carol Taylor"}
];
var searchName="John Smith"
console.log(studentDetails.filter(obj =>
obj.studentName.toLowerCase().indexOf(searchName.toLowerCase()) >= 0));

To run the above program, you need to use the following command;

node fileName.js.

Here, my file name is demo55.js.

Output

This will produce the following output −

PS C:\Users\Amit\JavaScript-code> node demo55.js
[ { studentName: 'John Smith' }, { studentName: 'john smith' } ]

Updated on: 03-Sep-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements