tags:

views:

106

answers:

5

i have a

var ID= "12,32,23,78";

 var i = ID.split(',');

if i do this then work fine but when it is only 12 then he give me 0. how i can solve this issue if i need to check if it have then how

+1  A: 
var i;
if (ID.indexOf(",") != -1)
    i = ID.split(',');
else
    i = ID;
teukkam
This should work assuming ID always contains either a comma separated list of integer or a lone integer without a comma.
teukkam
Except if ID is a **number** and not a string, then the call to `.search()` will fail.
Pointy
Well you're right, it's also assuming it's a string.
teukkam
A: 

Exactly like what you posted except you check for the presence of the seperator with JavaScripts .indexOf() string method.

ikanobori
Won't work when the variable "ID" is set to a number instead of a string.
Pointy
A: 
String.prototype.mySplit = function(sep) {
    return (this.indexOf(sep) != -1) ? this.split(sep) : [this];
};

Example:

//var ID= '12,32,23,78';
var ID= '12';

//Update
if (typeof(ID)=='number') ID += '';

var i = ID.mySplit(',');

alert(i[0]);
Otar
Won't work at all if ID is a number and not a string.
Pointy
This is completely unnecessary. `"12".split(",")` will return `[ "12" ]` - you don't need to write a separate function to get this behavior.
Andy E
You didn't mentioned that ID could be an integer, see updated code.
Otar
+5  A: 
Pointy
+1. Although the OP wasn't clear enough in his question, the other answers seem to be misunderstanding the inner workings of the *split()* method - if the separator character isn't in the string, *split()* will still work in exactly the same way - returning an array with only one element in it.
Andy E
Yes, I realize it was pretty vague, and indeed I don't know what he means when he says "he give me 0" of course, but it's almost certainly what the problem is.
Pointy
@Andy E: yup, though at least I found it suspicious that the split method was giving him 0, until Pointy clarified it was a data type thing. +1
BoltClock
A: 
    var ID= "12,32,23,78";

    var i = ID.split(',');

    will return [12,32,23,78]

    var ID= "12";

    var i = ID.split(',');

    will return [12] -- this is also an array

however you may do this

    var ID= "12";

    var i = ID.split(',') || ID;
Praveen Prasad