I believe you are asking for a demonstration of a textarea that can update some div in live time, replacing valid keys with their related value.
I first define the object s2mObj
which aims to define a relationship between a key string and its value.
Then I grab the textarea element from the dom, and add an event listener to the keyup
event. Whenever the key is released, I am going to execute the block of code inside, which is described as follows:
I will store the current input value into a constant variable named input
I preform some very basic validation of input using regex, before processing I replace all the characters that I would consider invalid with an empty string. I do this because 2H, as a string will not be found as a key however 2H will be, so by removing unexpected characters while I process, I avoid problems. This is mainly for demonstration purposes. You could add validation that fits your needs.
I take the validated/stripped input and split by spaces, the delimiter of choice. Now I have an array of each string segment. I map the array, and either replace with the value it is a key for, or the string err if it is not a valid key.
Now that I have processed the array, I convert back to a string with the .join
method, adding a comma to separate values.
Finally, I replace the innerText of my output area with the formatted string.
Hopefully this is helpful for you.
let s2mObj = {
"2H" : "Down B",
"6H" : "Forward B",
"236S" : "Quarter Circle Forward A",
}
document.querySelector("textarea")
.addEventListener("keyup", e => {
const input = e.target.value;
const inputValidated = input.replace(/[^a-zA-Z0-9 ]/g, "");
const arrOfIns = inputValidated.split(" ");
const arrOfOuts = arrOfIns.map(e => s2mObj[e] ? s2mObj[e] : "err");
const out = arrOfOuts.join(", ");
document.getElementById("output").innerText = out;
});
* {
box-sizing: border-box;
}
body {
margin: 0;
display: flex;
justify-content: space-around;
}
textarea, div {
width: 40%;
min-height: 200px;
display: inline-block;
}
div {
background-color: lightblue;
}
<textarea></textarea>
<div id="output"></div>
Try typing 2H 6H 236S
into the snippet!