Reputation: 51
I'm not really sure how to explain this, but basically, I have an input that takes in text. However, when I enter text that formatted exactly like an array, the program doesn't recognize it as an array, but rather a string.
How do I make my program recognize that my input is an array?
I input my value here:
<input id="inputArray" type="text" style="width:50%" placeholder="Your Array" oninput="storeArray(this.value)" onchange="storeArray(this.value)">
I store my value using the middleArray variable.
function storeArray(value) { //stores the input value
middleArray = value;
console.log(middleArray);
}
MiddleArray thinks that I have a string entered instead of an array even when the text is formated like an array.
What should I do to make the program recognize my input as an array?
Upvotes: 2
Views: 1022
Reputation: 23859
Not sure what exactly you're trying to do here. If you want to detect that the entered text is an array, you can do a JSON.parse
on the value, because the value fetched from the input box will always be a string.
function storeArray(value) {
middleArray = JSON.parse(value);
console.log(middleArray); // Will be an array
}
Note that the function above tries to parse the string as a JS object (array in your case). It may result in an error if you try to parse an invalid object string representation. You can always try to do a dirty checking before parsing, or use try-catch
blocks to mitigate any error:
function storeArray(value) {
value = value.trim();
middleArray = null;
if (value[0] === '[' && value[value.length - 1] === ']') {
middleArray = JSON.parse(value);
}
console.log(middleArray);
}
Upvotes: 1