Reputation: 18650
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?
Upvotes: 4
Views: 9161
Reputation: 6030
The fact that the alert shows 435,345,345345,56456
doesn't mean that the object is string, it could be Object
and Array
as well as their toString method implemented to display it in such way. For example the native array is also looks like that when alerting or converting to string, so you need to call toString method at first then split it by comma:
var firstInt = rowObject.toString().split(',')[0];
Upvotes: 0
Reputation: 8556
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.
Upvotes: 3
Reputation: 472
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]);
Upvotes: 4