Skip to content Skip to sidebar Skip to footer

How Do I Determine If A String Is An Array?

Given a string like '['chad', 123, ['tankie'], '!!!']', I need to return a boolean stating whether this string is a valid array or not. Am open to most solutions, including regex.

Solution 1:

Assuming you want to support some subset of the Javascript grammar, you can use regular expressions to remove whitespace and scalar literals and then check if what is remaining matches the nested pattern [,[,,,],,,].

let remove = [
    /\s+/g,
    /'(\\.|[^'])*'/g,
    /"(\\.|[^"])*"/g,
    /\d+/g,
];

let emptyArray = /\[,*\]/g;

functionstringIsArray(str) {

    for (let r of remove)
        str = str.replace(r, '');

    if (str[0] !== '[')
        returnfalse;

    while (str.match(emptyArray))
        str = str.replace(emptyArray, '');

    return str.length === 0;
}

console.log(stringIsArray("'abc'"));
console.log(stringIsArray(`['abc', ['def', [123, 456], 'ghi',,],,]`));
console.log(stringIsArray(String.raw`
          ['a"b"c', ["d'e'f", 
     [123, [[   [[["[[[5]]]"]]]]], 456], '\"\'""""',,],,]
`));

If you want all Javascript grammar to be supported (e.g. arrays that contain objects that contain arrays etc), you need a real parser. I wrote a module called litr that does exactly that - evaluate javascript literals, all of them:

const litr = require('litr'); // or <script src=litr.js>

myJsObject = litr.parse(myString);
console.log('is Array?', Array.isArray(myJsObject))

Basically, it's a thin wrapper around a PEG.js javascript grammar.

Solution 2:

If you need to support "any" string, you could use new Function() as a much safer alternative to eval().

functionstringIsArray(str) {
  try {
    returnnewFunction(`return Array.isArray(${str})`)();
  } catch {
    returnfalse;
  }
}

console.log(stringIsArray("abc"));
console.log(stringIsArray("['chad', 123, ['tankie'], '!!!']"));

Solution 3:

let strtotest = "['chad', 123, ['tankie'], '!!!']"Array.isArray(eval(strtotest))

This will return true if the array is valid. It will also throw an error if the syntax within the string is incorrect, so you'll have to handle that aswell.

I'd like to point out that eval is a horrible thing that you should never use, but seeing as the requirement of this question is crazy, I thought this solution is fitting.

Solution 4:

Maybe it's useful for someone else, you could do this too and it's in a few lines. if you define in 'a' the string that you want to analyze

a = "['chad', 123, ['tankie'], '!!!']";
Array.isArray( JSON.parse( a.replace(/'/g,'"') ) );

this will return true or false

Solution 5:

You should not use an eval (for obvious reasons of code injection). Parsing as JSON, what I will be doing, is not the same as an array, of course, but it's the closest you're going to get without the use of eval().

Something you can use is the JSON.parse method. Only downside here is that all strings must be delimited with double quotes (") due to the restriction of JSON.

Quick example using the nodejs interpreter:

> var arrayString = '["chad", 123, ["tankie"], "!!!"]';
undefined
> JSON.parse(arrayString);
[ 'chad', 123, [ 'tankie' ], '!!!' ]
> var notArrayString = 'asdas!asd1{}1239]1[';
undefined
> JSON.parse(notArrayString);
Thrown:
SyntaxError: Unexpected token a inJSON at position 0
> 

You could then use the Array.isArray method to check whether it is an array.

functionstringIsArray(str) {
    try {
        returnArray.isArray(JSON.parse(str));
    } catch (e) {
        returnfalse;
    }
}

stringIsArray('["chad", 123, ["tankie"], "!!!"]'); // returns truestringIsArray('something else, not an array'); // returns false

You could add a str.replace('\'', '"') if you don't care about the quotes.

Post a Comment for "How Do I Determine If A String Is An Array?"