+ 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.
6 Respuestas
+ 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?
+ 4
+ 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
+ 2
Or a regex that would do this maybe?
+ 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...
+ 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 😐