Convert HTML input string to JavaScript Array literal 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)=&gt; {   
      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}`;
      } 
    }); 
 &lt;form class="form"&gt;   
      &lt;fieldset&gt; 
        &lt;legend&gt;Enter array to parse&lt;/legend&gt;      
        &lt;input class="input" type="text"&gt;      
        &lt;input class="btn" type="submit" value="parse"&gt;  
      &lt;/fieldset&gt;
    &lt;/form&gt;
    &lt;div&gt;   
      &lt;p class="out"&gt; 
      &lt;/p&gt; 
    &lt;/div&gt;        






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?
The answer

What you're actually trying to do is only converting objects from Javascript notation to actual javascript objects. Now what if there was a well-specified data interchange format that was named "Javascript object notation"? Oh there is?

parsed = JSON.parse(inputField.value);


You're even using JSON.stringify already...



Other general advice


Don't use classes to identify unique elements. That's exactly not what classes are intended for. Instead use IDs.
Make use of the strict evaluation mode for javascript... "use strict"; 
You could avoid the e.preventDefault if you didn't use a submit button, but a normal button instead or listened to 'onblur'. I personally would prefer the last method the most, possibly combined with an 'onchange' listener with a timeout.
Always put braces around your stuffs, in this case around the throw new Error. This helps avoid bugs when changing the code later.