smulholland2
smulholland2

Reputation: 1163

Losing leading 0s when string converts to array

I have a textInput control that sends .txt value to an array collection. The array collection is a collection of US zip codes so I use a regular expression to ensure I only get digits from the textInput.

private function addSingle(stringLoader:ArrayCollection):ArrayCollection {
  arrayString += (txtSingle.text) + '';
  var re:RegExp = /\D/;
  var newArray:Array = arrayString.split(re);

The US zip codes start at 00501. Following the debugger, after the zip is submitted, the variable 'arrayString' is 00501. But once 'newArray' is assigned a vaule, it removes the first two 0s and leaves me with 501. Is this my regular expression doing something I'm not expecting? Could it be the array changing the value? I wrote a regexp test in javascript.

<script type="text/javascript">
  var str="00501"; 
  var patt1=/\D/;
  document.write(str.match(patt1));
</script>

and i get null, which leads me to believe the regexp Im using is fine. In the help docs on the split method, I dont see any reference to leading 0s being a problem.

**I have removed the regular expression from my code completely and the same problem is still happening. Which means it is not the regular expression where the problem is coming from.

Upvotes: 0

Views: 118

Answers (3)

stenrap
stenrap

Reputation: 39

I recommend just getting the zip codes instead of splitting on non-digits (especially if 'arrayString' might have multiple zip codes):

var newArray:Array = [];
var pattern:RegExp = /(\d+)/g;
var zipObject:Object;

while ((zipObject = pattern.exec(arrayString)) != null)
{
    newArray.push(zipObject[1]);
}

for (var i:int = 0; i < newArray.length; i++)
{
    trace("zip code " + i + " is: " + newArray[i]);
}

Upvotes: 1

hurrymaplelad
hurrymaplelad

Reputation: 27745

Running this simplified case:

var arrayString:String = '00501';
var re:RegExp = /\D/;
var newArray:Array = arrayString.split(re);
trace(newArray);

Yields '00501' as expected. There's nothing in the code you've posted that would strip leading zeros. You may want to dig around a bit more.

This smells suspiciously like Number coercion: Number('00501') yields 501. Read through the docs for implicit conversions and check if any pop up in your code.

Upvotes: 1

FailedDev
FailedDev

Reputation: 26920

What about this ?

/^\d+$/

You can also specify exactly 5 numbers like this :

/^\d{5}$/

Upvotes: 1

Related Questions