How to parse JavaScript array literal from HTML without using eval

4256 views javascript
4

I am trying to accept JavaScript array literals in an html text input.

The problem is that html text inputs are captured as text, such that an input of ['name', 'who', 1] becomes "['name', 'who', 1]".

The way I worked around the problem is by using eval in the code below:

HTML:

<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> 

JS:

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('invalid: input is  not a valid array' );
  } catch(err) {
    out.textContent = err.message;
  } 
}); 


What alternative way is there to converting JavaScript array literal html text inputs into JS array objects without using eval?

answered question

Replace single quotes with doubles in the string and it then becomes valid json

1 Answer

Have an answer?

JD

Please login first before posting an answer.