Losing leading 0s when string converts to array - actionscript-3

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.

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.

What about this ?
/^\d+$/
You can also specify exactly 5 numbers like this :
/^\d{5}$/

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]);
}

Related

Adding two javascript functions(depending on input)

I have put together a calculator what calculates a price, depending on user input. It works fine with one input, but now I have to scale it a little with a second user input. But here's the catch: the user might not want to put anything to the field, so it will be empty. And that's the thing that brakes my code. I could duplicate the calculator function and return the values and add those two together in a third function, but it will not work when there's an empty value.
Just for the sake of it, some trivial HTML code:
//When I only calculate with this user input, its easy
<input type="text" id="rocktext"><br>
// But how to consider this and do the same exact calculations like with the
//first one and add those two result together?
<input type="text" id="rocktext2"><br>
The code in the end should look like:
Take first user input, calculate the price(like in code below)
IF(!!) there is a second user input, calculate the price and add it to
the first one
Am I being a moron to try it with JS or just a moron in the firstplace?
Hope to hear from You, guys!
J.
The initial JS code is as follows:
function priceCalc() {
var inputs = document.getElementById("rocktext").value;
var length = inputs.length;
var accept = 6;
var initPrice = 8;
if (inputs<=accept){
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = initPrice + " dollars";
//I can also return the the value calculated here like so:
//retVal = initPrice;
}
else {
var intLength = parseInt(length, 10);
var lengthGap = intLength - accept;
var totals = lengthGap * 0.8 + initPrice;
var prec = totals.toPrecision(3);
// Since the code is much simpler right now i just put the result in HTML as follows:
document.getElementById("rockpricetotal").innerHTML = prec + " dollars";
// Here also the return clause can be possible with the calculation result like so:
//retVal = prec;
}
// And the final return as an alternative to the innerHTML :
// return retVal;
}
Making it scalable, you can add a class to all the inputs which may be in the function (something like calcInput), so you iterate all of them and if the value isn't empty (and if it's a valid number), you put it in the calculation.
Or you can just verify if the second input is empty, if so, calls functionOne, if not, calls functionTwo:
function twoDifferentWays() {
var valueOne = document.querySelector("#rocktext").value;
var valueTwo = document.querySelector("#rocktext2").value;
if (!!valueTwo && !isNaN(valueTwo)) {
callsFunctionOne(valueOne, valueTwo);
} else {
callsFunctionTwo(valueOne, valueTwo);
}
}

Is there a simple way to have a local webpage display a variable passed in the URL?

I am experimenting with a Firefox extension that will load an arbitrary URL (only via HTTP or HTTPS) when certain conditions are met.
With certain conditions, I just want to display a message instead of requesting a URL from the internet.
I was thinking about simply hosting a local webpage that would display the message. The catch is that the message needs to include a variable.
Is there a simple way to craft a local web page so that it can display a variable passed to it in the URL? I would prefer to just use HTML and CSS, but adding a little inline javascript would be okay if absolutely needed.
As a simple example, when the extension calls something like:
folder/messageoutput.html?t=Text%20to%20display
I would like to see:
Message: Text to display
shown in the browser's viewport.
You can use the "search" property of the Location object to extract the variables from the end of your URL:
var a = window.location.search;
In your example, a will equal "?t=Text%20to%20display".
Next, you will want to strip the leading question mark from the beginning of the string. The if statement is just in case the browser doesn't include it in the search property:
var s = a.substr(0, 1);
if(s == "?"){s = substr(1);}
Just in case you get a URL with more than one variable, you may want to split the query string at ampersands to produce an array of name-value pair strings:
var R = s.split("&");
Next, split the name-value pair strings at the equal sign to separate the name from the value. Store the name as the key to an array, and the value as the array value corresponding to the key:
var L = R.length;
var NVP = new Array();
var temp = new Array();
for(var i = 0; i < L; i++){
temp = R[i].split("=");
NVP[temp[0]] = temp[1];
}
Almost done. Get the value with the name "t":
var t = NVP['t'];
Last, insert the variable text into the document. A simple example (that will need to be tweaked to match your document structure) is:
var containingDiv = document.getElementById("divToShowMessage");
var tn = document.createTextNode(t);
containingDiv.appendChild(tn);
getArg('t');
function getArg(param) {
var vars = {};
window.location.href.replace( location.hash, '' ).replace(
/[?&]+([^=&]+)=?([^&]*)?/gi, // regexp
function( m, key, value ) { // callback
vars[key] = value !== undefined ? value : '';
}
);
if ( param ) {
return vars[param] ? vars[param] : null;
}
return vars;
}

Need to alter space from postal code in results array

Hi my requirement need to get postal code from
var address= results[0].formatted_address ;
this formatted value.
Because nether land address have "Danzigerkade 12,1013 AP Amsterdam,Netherlands" this kind of address. but i don't want postal code like this"1013 AP" . i need "1013AP" like this.
Please give me the solution.
Thanks in advance.
I don't recommend parsing the formatted_address to get the postal code or any other specific address fields. Instead, you should scan through the address_components and check the types array of each one to find the address field you need. This is much more reliable than parsing the formatted string.
Once you have the postal code, removing the space is trivial.
To find the postal code for an entry in your results array (e.g. results[0]), you can use code like this:
function getAddressComponent( result, type ) {
var components = result.address_components;
for( var i = 0; i < components.length; ++i ) {
var component = components[i], types = component.types;
for( var k = 0; k < types.length; ++k ) {
if( types[k] == type ){
return component;
}
}
}
return {};
}
var component = getAddressComponent( results[0], 'postal_code' );
var postalCode = component ? component.short_name : '';
var postalCodeNoSpace = postalCode.replace( ' ', '' );
console.log( postalCodeNoSpace );
Update in reply to your comment:
The code you're asking about with ? and : uses the conditional operator found in JavaScript and many other languages:
var postalCode = component ? component.short_name : '';
That works just like this longer form that should look more familiar:
if( component )
postalCode = component.short_name;
else
postalCode = '';
The idea was to not try to reference component.short_name if component itself is null or undefined, because of course that would be an error. In other words, to protect the program from crashing if getAddressComponent() does not find a postal code.
But interestingly enough, there's a bug in the way I was using it. Look at the last line of getAddressComponent():
return {};
Originally I was going to return null there - and then the code you asked about would have been correct - but for some reason I decided to return an empty object instead. So the code in question wasn't quite right with that change.
One way to fix this would be to go back to what I originally meant to do, and change the last line of getAddressComponent() from this:
return {};
to:
return null;

Google Docs Script Issue with Split through Function

First time poster here for Google Script related services, hopefully I put it in the right place! I'm encountering an error and I can't seem to find the right terminology to look up a solution. Below is the function. Within it I have a variable, string1, that I apply the split to. If I hard-code the value of the string (in the line commented out in the string), then it works and I receive the correct output. If, on the other hand, I try to pass that string into the function from another function, I receive the following error:
"TypeError: Cannot find function split in object Wed Oct 30 2013 09:00:26 GMT-0400 (EDT),danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found."
Note: My call to the function looks like this - formatEmailRow(completeEmailArray[i])
function formatEmailRow(rowToFormat) {
var formattedString = "";
var array1 = [];
var string1 = "";
///////////////////////
string1 = rowToFormat;
//string1 ="10/30/2013 9:00:26,danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found ";
///////////////////////
array1 = string1.split(",| ,|, ");
if (array1 != ""){
for (var i = 0; i < array1.length; i++) {
formattedString = formattedString + " " +(array1[i]);
}}
return formattedString;
}
Please help!
Thanks ahead of time, any advice is appreciated!
-Danno
You're getting that error because .split() isn't a method contained in the type of object you've passed in. Since you're new to this, it's worth a pause to read up on Objects and Methods - this is a quick overview.
You want to receive a String, but it seems that you're not. The problem will be with the code that's calling formatEmailRow().
My guess is that you're passing an array - probably all the cells in a row - but here's how you can check.
Add this line as the first line in your function:
Logger.log("rowToFormat = " + JSON.stringify(rowToFormat));
... then run, with your error. Check the logs - you want to see that you are getting a simple string. If you're getting an array, then you know what you need to fix. (Maybe you want to get the array after all!)

Regular Expression Help AS3?

I am working on a regular expression and I need to extract two parts of an expression that is being imported through a flashvars.
//sample data similar to what comes in from the flashvars. Note that the spaces are not after the and symbol, they are there because the html strips it.
var sampleText:String = "height1=60& amp;height2=80& amp;height3=95& amp;height4=75& amp;"
var heightRegExp:RegExp = /height\d/g; //separates out the variables
var matches:Array = sampleText.match(heightRegExp);
Now I need help isolating the values of each variable and putting them in an array...For instance, 60, 80, etc. I know I should be able to write this regular expression, but I just can't get the exec expression right. Any help would be really appreciated!
sorry for not answering the question with regexes directly. I would do this:
var keyvalues:Array = sampleText.split("& amp;");
var firstkey:String = keyvalues[0].split("=")[0];
var firstvalue:String = keyvalues[0].split("=")[1];
Would that help beside the fact, that it is not using RegEx?
Neither the =, & or the ; are special characters, so I think you can use
=|&
in a split call and then the values will be in the odd indices and the height2 style names would be in the even indices.
You can use URLUtil.stringToObject()
Something like this should work:
var s:String = "name=Alex&age=21";
var o:Object = URLUtil.stringToObject(s, "&", true);
However, if you're just getting the flashvars, you should pull them from the loaderInfo of the root.
this.root.loaderInfo.parameters;