Search for a string from a text file in java script

18,109

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.

Share:
18,109
Dilip wk
Author by

Dilip wk

Updated on June 04, 2022

Comments

  • Dilip wk
    Dilip wk almost 2 years

    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