简体   繁体   中英

Search inside txt file using javascript

On www.example.com/page_a/ is it possible to run a javascript code that searches for the text "hello" inside the file located at www.example.com/page_b/my_file.txt ?

Is this possible with javascript/jquery/ any other javascript framework?

Yes, it is possible and it is simplest with jquery.

You need to "get" contents of the text file like this:

$.get("www.example.com/page_b/my_file.txt", function(contents){
   //contents variable now contains the contents of the textfile as string

   //check if file contains the word Hello
   var hasString = contents.includes("Hello");

   //outputs true if contained, else false
   console.log(hasString);
})

Try using jquery $.get()

$.get("text file path",function(textString) {
    // handle the returned string ..
},"text/plain")

I am using indexOf() to search a string in a text file using JavaScript. Here is the code

$.get("www.example.com/page_b/my_file.txt", function(contents){
   var str = "Hello";
   if(contents.indexOf(str) != -1){
       console.log(str + " found");
   }
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM