Validate if string is correctly formed 2D array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

Validate if string is correctly formed 2D array

I'm making a tutorial site based on interactive quizzes for stuff that the internet currently only has decent static content for, such as trees... What I'd like to do atm is parse a user input string to check if it is a valid 2D array. If it is, I pass it to my tree generator, if not display a hint message to the user. Thing is, I can just parse for the square brackets in the right order, fair enough, but I'm wondering if there are any JavaScript functions or libraries that might take a bit of the hassle out of checking if user input is of a particular type. Anyone know of anything? I tried eval but that generates a bunch of errors which mess up my program and is a security nightmare anyway.

4th Oct 2019, 2:07 PM
Peter David Carter
Peter David Carter - avatar
6 Answers
+ 5
Peter David Carter I just now saw your question and agree that JSON.parse will be a good way to evaluate. I'm sure Regex would be another option to consider as well. Do you have any test strings you can share?
4th Oct 2019, 4:27 PM
David Carroll
David Carroll - avatar
4th Oct 2019, 2:38 PM
Peter David Carter
Peter David Carter - avatar
+ 3
Peter David Carter I completely missed your response. Sorry about that. Here is a simple Regex that might need more testing. But I think it does the job for the most part. I think the JSON approach is better. https://code.sololearn.com/WTcwWtWf3AV4/?ref=app
8th Oct 2019, 5:44 AM
David Carroll
David Carroll - avatar
+ 2
Or a regex that would do this maybe?
4th Oct 2019, 2:52 PM
Peter David Carter
Peter David Carter - avatar
+ 2
Ah ha! Finally tracked down this: https://stackoverflow.com/questions/13630014/convert-string-to-a-multidimensional-array answer. Looks like good 'ole JSON.parse will do the trick. Let's seeeeee...
4th Oct 2019, 4:00 PM
Peter David Carter
Peter David Carter - avatar
+ 2
David Carroll Sure, one simple one would be [[1],[2,3]] which would be a root node with two children. Hopefully I'm modelling this right 😐
4th Oct 2019, 4:34 PM
Peter David Carter
Peter David Carter - avatar