How could I manipulate this array in Javascript for this kind of error checking?

How can I make Javascript check an array and make sure that there's no error committed after the comma separating each element of the array .. For example a user may form an array with two commas in a row separating an element instead of one comma .. Not just comma , any other wrong input.

var cars=["Saab",,"Volvo","BMW"]; // Here , this array has an error , there's a double comma .
var cars=["Saab",*"Volvo","BMW"]; // this array has an error , there's an asterix.
var cars=["Saab","Volvo","BMW"];  // this array is the right one.

Here's the wrong array

What Javascript function or solution could I use to make sure an array is checked and no error is within it .. Only elements and separating commas with no space in between.

Your help would be so much appreciated.



Use a static code analyzer such as JSLint or JSHint.

The latter is available as a JavaScript library in addition to the web-hosted flavor.


Given that you are trying to validate user-entered data, I'd suggest reevaluating your approach.

You should not require end-users to enter data in valid JavaScript syntax; this is annoying to your users.

Instead, I'd just have a textarea and instructions.


This is far easier for humans to deal with, and parsing is super simple:

var cars = document.getElementById('carstextarea').value.split('\n');
// => ["Saab","Volvo","BMW"]

You can use jslint takes a JavaScript source and scans it ,

visual studio, netbeans or eclipse have a plugin for that.

Good Luck!!!


Your second cars example with the * in it won't compile.

To check for double commas, you can iterate over the array and check for an undefined value.

for(var i = 0; i<cars.length; i++) {
if(cars[i] === undefined) {
// do something

Alternatively you could try and catch this before you generate the array. Is there a way to check for an empty row inputted by the user?


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.