使用 JavaScript 過濾一個字串陣列,匹配不區分大小寫的子字串?


首先,讓我們建立一個字串陣列 −

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

現在,匹配不區分大小寫的子字串,在其中使用 filter() 和 toLowerCase() 的概念。以下是程式碼 −

示例

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));

要執行以上程式,你需要使用以下命令;

node fileName.js.

此處,我的檔名是 demo55.js。

輸出

這將產生以下輸出 −

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

更新於:03-Sep-2020

3 千+ 次瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始吧
廣告