homepage/toys/grepdict/grepdict.js

58 lines
1.2 KiB
JavaScript
Raw Normal View History

2019-10-05 19:49:01 -06:00
// jshint asi:true
var words
function addWords(wl) {
words = wl.split("\n")
let re = document.querySelector("#regexp")
re.value = ""
re.disabled = false
re.focus()
2019-10-26 16:46:03 -06:00
re.dispatchEvent(new Event("input"))
2019-10-05 19:49:01 -06:00
}
function regexInput(e) {
2019-10-26 14:55:21 -06:00
let re = new RegExp(e.target.value, "u")
2019-10-05 19:49:01 -06:00
let matches = document.querySelector("#matches")
while (matches.firstChild) {
matches.firstChild.remove()
}
let nmatches = 0
for (let word of words) {
if (word.match(re)) {
let li = matches.appendChild(document.createElement("li"))
li.textContent = word
nmatches += 1
2022-01-25 07:15:48 -07:00
if (nmatches > 600) {
2019-10-05 19:49:01 -06:00
li.textContent = "…"
break
}
}
}
}
2019-10-26 16:05:15 -06:00
function anchorToggle(e) {
let re = document.querySelector("#regexp")
let val = re.value.replace(/^\^|\$$/g, "")
if (val == re.value) {
val = "^" + val + "$"
}
re.value = val
re.focus()
2019-10-26 16:46:03 -06:00
re.dispatchEvent(new Event("input"))
2019-10-26 16:05:15 -06:00
}
2019-10-05 19:49:01 -06:00
function init(e) {
fetch("words.txt")
.then(r => r.text())
.then(addWords)
document.querySelector("#regexp").addEventListener("input", regexInput)
2019-10-26 16:05:15 -06:00
document.querySelector("#anchor").addEventListener("click", anchorToggle)
2019-10-05 19:49:01 -06:00
}
2019-10-26 14:55:21 -06:00
window.addEventListener("load", init)