node.js - How do I check if the exact string I am searching for is listed in a file? -


i trying write function search given string(exact string) in file , prompt if listed in file in node.js. have tried below script lists string if search string listed substring in file. have message.txt include following words:

bat bait  can  cat 

my script search string in file

var fs = require('fs'); fs.readfile('message.txt', function (err, data) {     var searchstr = "bat";       if (err) throw err;         if(data.indexof(searchstr) < 0){                console.log("string not found");       }         else{             console.log("string found!");         } }); 

so, here searching bat using searchstr apparently output "string found". now, problem is, if give at search string, output "string found" because "at" substring of bat , cat per file. but, i'd function output "string not found" when search at.

you can use regular expression here:

/\bat\b/ 

will match at surrounded word boundaries. need change code bit:

var fs = require('fs'); fs.readfile('message.txt', function (err, data) {     var searchstr = "bat";     var pattern = new regexp("\b" + searchstr + "\b");     if (err) throw err;      if (pattern.test(data) === false) {         console.log("string not found");     } else {         console.log("string found!");     } }); 

depending on exact requirements might have change regular expression. example, might want test at surrounded whitespace instead: /\sat\s/.


Comments

Popular posts from this blog

magento2 - Magento 2 admin grid add filter to collection -

Android volley - avoid multiple requests of the same kind to the server? -

Combining PHP Registration and Login into one class with multiple functions in one PHP file -