user3234749
user3234749

Reputation: 11

javascript Check type of attribute

Is it possible to get the type of result by query for example

var titles = $(this).attr('name');

In case that the name is: ["str1", "str2"], I want to identify that the titles is a list/array. Is it possible and how can I know if it is a string or array, and in case that it is array to get each value from the array.

Upvotes: 0

Views: 1367

Answers (2)

Custodio
Custodio

Reputation: 8954

After parsing the content of $(this).attr('name'). (It's always a string)

In order to check if the object is an array you can:

Array.isArray([1, 2, 3]);  //TRUE
Array.isArray("Some title");  //False

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1075209

The value of an attribute is always a string, never an array. If you then want to interpret that string as something else, you need to check that it fits the format you expect (perhaps with a regular expression) and parse/convert it to that format.

In your case, for instance, you might see if it's valid JSON (although ["str1", "str2"] is a very unusual value for the name attribute of an element):

var titles = $(this).attr("name");
var parsed = null;
try {
    parsed = JSON.parse(titles);
}
catch (e) {
}
// Here, if `parsed` is not `null`, it was valid JSON and is the array

Upvotes: 2

Related Questions