Home > database >  How To Create Javascript Array From Single HTML Input?
How To Create Javascript Array From Single HTML Input?

Time:09-18

<input type="text" id="blah" value="'a1','a2'">
<script>
dd=document.getElementById('blah').value

cars = [dd]
console.log(cars)
</script>

When I try to do it in console I see the result: ['"a1", "a2"'] This is why I can't use it as array. What I want is: ["a1","a2"] I want to use it as array. How can I do it? Is it possible?

CodePudding user response:

<input type="text" id="blah" value="'a1','a2'">
<script>
dd=document.getElementById('blah').value

cars = dd.split(',').map(e=>e.substr(1, e.length-2));
console.log(cars)
</script>

CodePudding user response:

I'm not sure about your situation but based on your current problem you can do something like this.

<script>
   dd=document.getElementById('blah').value

   cars = dd.replace(/[']/g,"").split(",")
   console.log(cars)
</script>

CodePudding user response:

Also an option with RegExp split:

// Get value
const dd = document.getElementById('blah').value;
// Parse
const cars = dd.split(/'(\w )'[,]*/).filter(e => e);
console.log(cars)
<input type="text" id="blah" value="'a1','a2'">

CodePudding user response:

You could try:

cars = dd.split(",")

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split?retiredLocale=de

  • Related