hussain
hussain

Reputation: 7113

How to make search case insensitive using nodejs?

I have a search function so i have input from client Str if that matchs with content in file send that in response. Lets assume i have text in file Lorem now if i search as lorem from client, it sends empty array because of case sensitive. How can i make search case insensitive ?

searchService.js

var searchStr;
function readFile(str, logFiles, callback) {
        searchStr = str;
        // loop through each file
        async.eachSeries(logFiles, function (logfile, done) {
            // read file
            fs.readFile('logs/dit/' + logfile.filename, 'utf8', function (err, data) {
                if (err) {
                    return done(err);
                }
                var lines = data.split('\n'); // get the lines
                lines.forEach(function(line) { // for each line in lines
                    if (line.indexOf(searchStr) != -1) { // if the line contain the searchSt
                        results.push({
                        filename:logfile.filename,
                        value:line
                        });
                    }
                });
                // when you are done reading the file
                done();
            });

Upvotes: 0

Views: 3602

Answers (2)

You can use regex using .match(/pattern/i). The /i makes the pattern search case insensitive.

if ("LOREMMMMMM".match(/Lorem/i)) console.log("Match");

Upvotes: 1

Andrew Brooke
Andrew Brooke

Reputation: 12173

You can make use of toLowerCase()

if (line.toLowerCase().indexOf(searchStr.toLowerCase()) != -1) { ...

Upvotes: 5

Related Questions