Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first item from comma delimited object

Hi I have an object rowObject passed into a javascript function. When I inspect it by putting it into an alert I see something like:

435,345,345345,56456

What I want to achieve is to get the first integer ie. 435 from the list.

I know how to do this in server side code but client side code.

Can someone please help me with this?

like image 322
AnonyMouse Avatar asked Sep 04 '25 03:09

AnonyMouse


2 Answers

Assuming that your rowObject is a string, you can use .split() to split the comma delimited list. At this point you can access the array of items by index and get the first element.

http://www.w3schools.com/jsref/jsref_split.asp

An Example

var rowObject = "435,345,345345,56456";
var splitRowObject = rowObject.split(',');
if(splitRowObject.length > 0)
    alert(splitRowObject[0]);
like image 119
Scruffy The Janitor Avatar answered Sep 05 '25 23:09

Scruffy The Janitor


alert() is calling objects toString() method, so you don't know the structure of the object. It is a good idea to use console.log instead for logging objects as in modern browsers it will allow you to explore structure of the object in the console window.

One of the solutions you can do without knowing the structure is:

var firstInteger = +rowObject.toString().split(',')[0] // 435

That works if rowObject is string, array or everything else :).

EDIT: Putting + before the string will try to convert it to a number.

like image 22
kubetz Avatar answered Sep 05 '25 23:09

kubetz