Reputation: 3659
I am wanting to convert a string into 2 variables..
I have created a variable and I am using substring to split it, however I can't seem to get it working.
If I create a alert message it display's the orignal variable that I want split up (so I know there is something there)
My code looks like this:
// variable 'ca' is set from a XML Element Response
alert(ca); // displays a string (eg. 123456789) - which does display fine
alert(ca.substring(0,1)); // should alert 1 but it stops and nothing is displayed
but I add ca = "123456789"; as below, it works..
ca = "123456789";
alert(ca); // displays a string (eg. 123456789) - which does display fine
alert(ca.substring(0,1)); // should alert 1 but it stops and nothing is displayed
however the variable ca has something set and is display right before the substring is used..
anyone know what I might be doing wrong?
Upvotes: 0
Views: 367
Reputation: 13632
My guess is that ca
doesn't contain a string but a number.
Does it work when you cast the variable to a string?
alert(String(ca).substring(0,1));
(Note that you can check what a variable contains with the typeof
operator:
console.log(typeof ca);
// number
console.log(typeof String(ca));
// string
UPDATE: both ca.toString()
and String(ca)
should work, but I personally prefer String(ca)
since that will also work if ca is null
or undefined
.
Upvotes: 1
Reputation: 700680
Your variable doesn't contain a string, it contains something else, probably a number.
Convert the value to a string, to be able to use string methods on it:
ca = ca.toString();
Upvotes: 2