简体   繁体   English

使用javascript在txt文件中搜索

[英]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 ?www.example.com/page_a/上是否可以运行 javascript 代码来搜索位于www.example.com/page_b/my_file.txt的文件中的文本“hello”?

Is this possible with javascript/jquery/ any other javascript framework? javascript/jquery/任何其他javascript框架可以做到这一点吗?

Yes, it is possible and it is simplest with jquery.是的,这是可能的,而且使用 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()尝试使用 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.我正在使用 indexOf() 在使用 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");
   }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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