Truvia
Truvia

Reputation: 370

Javascript / Jquery Search if a word exists in a string

I'm definitely a newbie and am trying a practice project. Its basically an anagram game where the user clicks on certain letters to put together a word. I now need to check that it is actually a word. I've made a text file containing all the words in the dictionary (copied from someones website as its just a practice project). I've managed to get it so that if I can console.log the words.

function Searchtext(){
    $.get('words.txt', function(data) {
console.log(data);



}, 'text');
    }

Now I want to search the words to see if the player's answer ( a string which is declared in a variable called playeranswer ) is in the list. I don't need it to return the word, only whether it is there or not. N.B. it has to be exact so that for example if the user entered "ender" which isnt a word, it wont come back true because it finds the word "render". Maybe something with the .length will help?

How would I go about doing this?

Thanks for any help.

Upvotes: 1

Views: 9774

Answers (4)

Ian
Ian

Reputation: 50905

Since $.get is asynchronous, you'll have to set it up a little differently. I'd do this:

function Searchtext(name, callback) {
    $.get('words.txt', function(data) {
        data = data.split("\n");
        var contains = (data.indexOf(name) > -1);
        callback(contains);
    }, 'text');
}

Depending on how the text file is setup, you might have to change .split("\n") (which splits up the words into an array, if they're each on a line) to .split(" ") (which splits up the words into an array, if they're separated by a space).

And you'd call it like:

SearchText(playername, function (matched) {
    if (matched) {
        // Name was in list
    } else {
        // Name wasn't in list
    }
});

DEMO: http://jsfiddle.net/Fkr5B/

In the demo, I had to simulate the AJAX request.

Upvotes: 3

Memolition
Memolition

Reputation: 494

I've made this simple script, hope it helps

$(document).ready(function(e) {
    function parseData(data) {
    $('#inpu').blur(function() {
        var str_to_search = $.trim($('#inpu').val());
        if(str_to_search.length) {
            var search_res = data.search(str_to_search);
            if(search_res != -1) {
                alert('Word Valid!');
            } else {
                alert('Word no valid');
            }
        }
    });
}
$.get('to_search.txt', parseData).fail(function() { alert('error');});
});

Upvotes: 0

user428517
user428517

Reputation: 4193

I would use a regular expression (using a RegExp object) for this. Here is a simple example that tries to match a word in two different strings of words:

var word_to_match = 'ender';
var string_of_words = 'a string containing the word ender, this will match';
var second_string_of_words = 'a string that will not produce a match';

//use \b to match on word boundaries
var filter = new RegExp('\\b' + word_to_match + '\\b', 'gi');

if(string_of_words.match(filter)) {
    alert('found word: ' + word_to_match);
} else {
    alert('did not find word: ' + word_to_match);
}

if(second_string_of_words.match(filter)) {
    alert('found word: ' + word_to_match);
} else {
    alert('did not find word: ' + word_to_match);
}

You'll see the first if statement passes, while the second fails. A little reading might be required, but you should be able to expand this example to fit your use case.

Upvotes: 2

dragos2
dragos2

Reputation: 155

You should first parse the data variable and place the words into an Array. Then you can test if the user entered a valid word by checking if your Array contains that word.

var Dict = new Array("render", "bender", "word");

function isValid(word){
    if(Dict.indexOf(word) == -1) 
        return false; //the word is not valid
    return true; //the word is valid
}    

Upvotes: 0

Related Questions