Home > front end >  How do I turn this search function into case insensitive?
How do I turn this search function into case insensitive?

Time:10-12

As a newbie, I have been having problems converting this search function to being case insensitive. It is currently working as it is but it only shows the results if it matches its exact case like a search of "Item 1" will output "Item 1" but would not if it is "item 1".

function processorOfFormSearch(formObject){  
var result = "";
if(formObject.searchtext){    //***********Execute if form passes search text
  result = search(formObject.searchtext);
}
return result;
}

//SEARCH FOR MATCHED CONTENTS 
function search(searchtext){
var spreadsheetId   = globalVariables().asArray.spreadsheetId;
var dataRange        = globalVariables().asArray.dataRange;
var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRange).values;
var ar = [];

data.forEach(function(f) {
   if (~f.indexOf(searchtext)) {
   ar.push(f);
   }
 });
return ar;
}

CodePudding user response:

You can use new RegExp with your searchText as the first parameter, and 'i' as the second parameter, indicating case insensitive. Then run your data values through it using .test() I know your example uses indexOf so you may have to make some adjustments, but the general idea is there.

Sample Script

const data = ['Item 1', 'Item 2', 'item 3', 'item 1', 'ITEM 1']
const searchText = 'Item 1'
let arr = []

const validateText = (query) => {
  let regex = new RegExp(searchText, 'i')
  return regex.test(query)

}

data.forEach(d => {
  if (validateText(d)) {
    arr.push(d);
  }
})

console.log('results of arr',
  arr
)

CodePudding user response:

Perhaps something like this

function search(searchtext) {
  var spreadsheetId = globalVariables().asArray.spreadsheetId;
  var dataRange = globalVariables().asArray.dataRange;
  var orow = dataRange.getRow();
  var data = Sheets.Spreadsheets.Values.get(spreadsheetId, dataRange).values;
  var ar = [];
  dataRange.createTextFinder(searchtext).matchCase(false).findAll().forEach(r => {
    ar.push(data[r.getRow() - orow]);
  });
}

CodePudding user response:

Are they strings? Why not use a filter that matches the data set to lowercase and the search string set to lowercase?

const result = data.filter((data) => {
  return data.toLowerCase() === searchtext.toLowerCase();
});
  • Related