<h1>
TRIE Spellchecker
</h1>
<h4>
Enter a word to add to dictionary: <input type="textbox" id="tbWord" onkeyup="change(value)"/>
</h4>
<input type="button" id="btnAdd" value="Add Word" onclick="addWord();" />
<input type="button" id="btnSpellcheck" value="Check Spelling" onclick="check();" />
<br/><br/>
<div id="output">
</div>
<div id="output2">
</div>
<div id="output3">
</div>
JavaScript
debugger;
//trie function
function Trie(key) {
this.key = key;
}
Trie.prototype.addToTrie = function(word) {
var node = this;
var len = word.length;
var current;
for (var i = 0; i < len; i++) {
current = word[i];
node = node[current] || (node[current] = new Trie(current));
}
node.value = word;
node.word = word;
}
Trie.prototype.checkSpelling = function(word) {
var node = this;
var len = word.length;
for (var i = 0; i < len; i++) {
if (!(node = node[word[i]])) break;
}
return (i == len) ? "Word exists" : "Word does not exist or is misspelled";
}
var dictionary = new Trie();
dictionary.addToTrie("I");
dictionary.addToTrie("in");
dictionary.addToTrie("into");
dictionary.addToTrie("inlet");
dictionary.addToTrie("inn");
dictionary.addToTrie("inner");
dictionary.addToTrie("innate");
dictionary.addToTrie("ink");
function addWord() {
document.getElementById("output3").innerHTML = "";
var newWord = document.getElementById("tbWord").value;
dictionary.addToTrie(newWord);
document.getElementById("output2").innerHTML = "Added the word " + newWord + " to the dictionary.";
}
function check() {
var newWord = document.getElementById("tbWord").value;
document.getElementById("output2").innerHTML = "";
document.getElementById("output3").innerHTML = "Checked the following word for spelling: " + newWord;
document.getElementById("output2").innerHTML = dictionary.checkSpelling(newWord);
}
var w = ["I", "in", "into", "inlet", "inn", "inner", "innate", "ink"];
function matchWords(input) {
var reg = new RegExp(input.split('').join('\\w*').replace(/\W/, ""), 'i');
return w.filter(function(input) {
if (input.match(reg)) {
return input;
}
});
}
function change(input) {
var complete = matchWords(input);
document.getElementById("output").innerHTML = complete;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.