Search for a string from a text file in java script

走远了吗. 提交于 2019-12-11 05:25:29

问题


I am creating a Dictionary app for mobile using Java Script. I have stored Dictionary source in a separate file. My doubt is how to access that file and search for particular string using Java Script.

function dic() {
    var word = document.getElementById("wo").value;
    var dictionary = new Array("Java","Python","Swift","HTML","PHP");
    var flag = 0;
    for(var i = 0; i < dictionary.length; i++) {
        if(dictionary[i] == word) {
            document.getElementById("result").innerHTML = "Element Found";
            flag = 1;
            break;
        }
    }
    if(flag == 0)
        document.getElementById("result").innerHTML = "Element Not Found";  

}

This script checks for the word in array. I want to replace the array words to a text file. Thanks in advance


回答1:


To access the file, use jQuery's .get() function. This can also be done with XMLHttpRequests in pure JS but jQuery will handle cross-browser compatibilty for you.

To get the file:

$.get("http://www.example.com/path/to/file.txt",function(returnedData) {
    $("#element").text(returnedData);
},"text/plain");

This will load the contents of http://www.example.com/path/to/file.txt into the div with ID element. Assuming each dictionary word is on a new line, you can then separate them into an array with the following:

var text = $("#element").text();
var words = text.split("\n");
var dictionary = new Array();
for(var i=0; i < words.length; i++) {
    dictionary[i] = words[i];
}

Now you have the dictionary words in your array and can search for them with your existing code (with a couple of corrections):

function dic() {
    var word = document.getElementById("wo").value;
    // var dictionary = new Array("Java","Python","Swift","HTML","PHP");
    // This line is unnecessary; use the dictionary var already created.
    var flag = 0;
    for(var i = 0; i < dictionary.length; i++) {
        if(dictionary[i] == word) {
            document.getElementById("result").innerHTML = "Element Found";
            flag = 1;
            break;
        }
        if(i == dictionary.length - 1) {
            document.getElementById("result").innerHTML = "Element Not Found"; 
        }
    }
}

That should leave you with the right answer.

Hope this helps.

EDIT:
Part of the code in my second code sample is unnecessary and only there for clarity; you can in fact just state that var dictionary = text.split("\n");, which will yield the same result.



来源:https://stackoverflow.com/questions/24231617/search-for-a-string-from-a-text-file-in-java-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!