Sequenzia
Sequenzia

Reputation: 2381

Stop JavaScript from truncating leading 0

I normally use the following code to get PHP variables into JavaScript:

echo("var zipCode = " . $zipCode . ";");

This works fine but on zip codes that start with a 0 it is truncating it.

I am trying to figure out a way to keep the leading 0.

Any help would be great.

Thanks

Upvotes: 3

Views: 1854

Answers (1)

Ian
Ian

Reputation: 50905

Make it a string then:

echo("var zipCode = '" . $zipCode . "';");

Notice the two ' characters before and after the concatenating of $zipCode.

I'm sure $zipCode is a string in your PHP, but when you echo it, it doesn't include the quotes. That means your resulting Javascript would look like:

var zipCode = 01234;

And there's no reason to store it as a number (incorrect number, in this case, since it will think it's an octal number).

So by adding the ' characters, the resulting Javascript becomes:

var zipCode = '01234';

And should be just fine with manipulating, since you should really only be doing string manipulations on a zip code anyways.

If, for whatever reason, you decide that you need the Number form of the zip code, you can use this in Javascript:

var zipCodeNum = parseInt(zipCode, 10);

The important part is the , 10, as this will force the conversion to be in base 10, ignoring any leading 0s.

Upvotes: 6

Related Questions