I want to compare a string with a list of strings

The first string comes from a textbox where you write and the list of strings is written on a .json/.txt file. I don’t know how to read the file and compare it.

example:

input:
word1

.json/txt file

word1
word2
word3
word4

I need to know how to read the file and compare it with all the words of the file
This is the code that compares it it gets the variable from a file but the code its too large

function wordcompare() {
    var typed = document.getElementById("word").value;
  
    if (typed === word1 ||  typed === word2) {
      alert("Correct word");
    } else {
      alert("Incorrect word");
    }
  }
  
  document.querySelector("button").addEventListener("click", wordcompare);

This is the json with the words i want if its possible just to need to write the list of words and dont have to write var 1, var2 ,var 3 till 700


var 1 = "word1";
var 2 = "word2";

I need to know how to read the file…

There are plenty of resources you can find on how to read a json file.

and compare it with all the words of the file

Well, I like to break problems into smaller problems. This is a simple algorithm problem. I would expect to loop through it and check each element against your target. You could use a simple for loop but there are also prototype methods like find, findIndex, map, reduce, or forEach depending on what you want the result to be.

Again, I like to break up big problems into smaller problems. Why not create some “dummy data” with the same shape of what you expect to end up with. See if you can find a string in an array of strings.

1 Like

Im not understanding what you mean

You’re going to have to be more specific if you want to me to clarify something.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.