Using regex isn't going to be all that simple. I agree with @apple apple that it would make sense to look for a library. I was intrigued about how long it would take to stub out a basic one by hand so I whipped this up, feel free to use/improve on it to optimize for working with that larger list that you have.
The basic gist is that you set a threshold for similarity in length between the input and expected output, and a minimum letter match score that you want to aim for.
For each word in your set, you run a comparison function between that word and the input. In the comparison function, you test each letter of the input against the word to see if it exists - if so, remove that letter from the word and move to the next one (to avoid inflated scores from multiple matches to the same letter: i.e. the string aaaaaa
would score a 6 against apple
if the a
isn't removed after the first match)
If you wanted to enable multiple suggestions, you could replace the while(++i < listlen)
loop with wordlist.filter
, and return all words that fall above a certain score threshold.
const wordlist = ["apple", "orange", "mango", "fruit", "banana", "kiwi", "grapefruit"],
listlen = wordlist.length,
wordLengthDifferential = 1,
scoreDifferential = 3
function compare(str, word){
let score = 0
str = str.split('')
word = word.split('')
while(str.length){
let idx = word.indexOf(str.pop())
if(idx > -1){
++score
word.splice(idx, 1)
}
}
return score
}
function getSuggestion(str){
let highScore = 0, suggestion = null, i = -1
while(++i < listlen){
let word = wordlist[i]
if(Math.abs(word.length - str.length) <= wordLengthDifferential) {
let score = compare(str, word)
console.log(str, word, score)
if(score > highScore && score >= scoreDifferential){
suggestion = word
highScore = score
}
}
}
return suggestion || "no relevant matches"
}
document.querySelector('button').onclick = e => console.log(getSuggestion(document.querySelector('input').value))
document.addEventListener('keydown', e => {
if(e.keyCode == 13) console.log(getSuggestion(document.querySelector('input').value))
})
<input type="text" /><button>Go</button><em>(or press enter)</em>