0

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?

3
  • If I have to guess maybe you're looking for ca value while ajax call is still running... could you post the relevant code please? Commented Jun 5, 2012 at 7:48
  • Your xml response might have some spaces at the beginning. Try - alert('>>' + ca.substring(0,1) + '<<' ); Commented Jun 5, 2012 at 7:49
  • Please tell me you have checked for errors on the page... Commented Jun 5, 2012 at 7:51

2 Answers 2

2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

You where spot on, it was a number and I needed to convert it to a string. - Your a life saver.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.