I am trying to accept JavaScript array literals in an HTML text input.
The problem is that HTML text inputs are captured as strings, such that an input of ['name', 'who', 1]
becomes "['name', 'who', 1]"
.
My intention is for the following samples to yield the corresponding outputs.
"['river',"spring"]" // ["river","spring"]
"[{key:'value'},20,'who']" // [{"key":"value"},20,"who"]
The way I worked around the problem is by using eval in the code snippet below:
const form = document.querySelector('.form');
const inputField = document.querySelector('.input');
const btnParse= document.querySelector('.btn');
const out = document.querySelector('.out');
form.addEventListener('submit', (e)=> {
e.preventDefault();
try {
parsed = eval(inputField.value);
if(Array.isArray(parsed)) {
out.textContent = JSON.stringify(parsed);
} else throw new Error('input is not a valid array' );
} catch(err) {
out.textContent = `Invalid input: ${err.message}`;
}
});
<form class="form">
<fieldset>
<legend>Enter array to parse</legend>
<input class="input" type="text">
<input class="btn" type="submit" value="parse">
</fieldset>
</form>
<div>
<p class="out">
</p>
</div>
My solution, however, allows for the execution of any Javascript code inputted into the text field, which is a huge vulnerability.
What alternative way is there to converting JavaScript array literal HTML text inputs into JS array objects without using eval?
eval
doesn't exist. Don't be tempted to use it. For most applications, there are much better alternatives available. Anyway, I think you're asking the wrong question and that JSON is your answer. \$\endgroup\$