Separate strings in a string with Actionscripts3 - actionscript-3

I'm trying to separate two part of a string, one is Title one is Value, RegExp is confused me. I need your help to solve this thanks
var pattern2:RegExp = new RegExp("TZ_NUM_ANSWER:Telegram code([0-9.-]+)");//TZ_NUM_ANSWER:Telegram code 32263
var data2:Object = pattern2.exec(response);
if (data2 != null && data2[1] != null)
{
var value2:Number = parseFloat(data2[1]);
trace("TZ_NUM_ANSWER " + value2);
txt_BUY1.text = String(value2);
}
Output:
TZ_NUM_ANSWER:Telegram code 32263
It must be:
"TZ_NUM_ANSWER:" "Telegram code 32263"

The result of split is an Array you can access to Array indexes and assign them to a variable.
var STR1:String = "TZ_NUM_ANSWER:Telegram code 32263";
var STR2:String;
var STR3:String;
trace(STR1.split(":"));
STR2 = STR1.split(":")[0];
STR3 = STR1.split(":")[1];
trace (STR2);
trace (STR3);
Result:
TZ_NUM_ANSWER
Telegram code 32263

Don't use RegEx for simple stuff. All you need is basic string methods:
response.split(":");

Related

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;

Split textfield value in 2 parts and put each part in a var

I have a textfield, that has a text value: France Paris. Now I need to know how I can take that string, cut it in 2 parts (France and Paris) and put those two parts in a var. So:
<textfield id="field1" text="France Paris">
and somewhere i should get
var1 = France;
var2 = Paris;
I know there is a split string command, but I'm not familiar with any of this stuff.
For this you could use the split() method on your String. This will split your String and put the values in an Array. You can use it like this:
var yourString:String = "France Paris";
var splitString:Array = yourString.split(" ");
var firstWord:String = splitString[0];
var secondWord:String = splitString[1];
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/String.html#split()

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

Dynamic variables in ActionScript 3.0

so.... eval() out of the question, any idea to do this? I also don't know how to use "this" expression or set() in actionscript 3 ( i seem couldn't find any complete reference on it ), just say through php file a multiple variable (test1, test2, test3,...) sent by "echo", how the flash aplication recieved it? I'm trying not to use xml on mysql to php to flash aplication. Simply how to change a string to a variable ?
example
(in as3-actions frame panel)
function datagridfill(event:MouseEvent):void{
var varfill:URLVariables = new URLVariables();
varfill.tell = "do it";
var filler:URLRequest = new URLRequest();
filler.url = "http://127.0.0.1/flashdbas3/sendin.php";
filler.data = varfill;
var filling:URLLoader = new URLLoader();
filling.dataFormat = URLLoaderDataFormat.VARIABLES;
filling.load(filler);
filling.addEventListener(Event.COMPLETE, datain);
function datain(evt:Event){
var arraygrid:Array = new Array();
testing.text = evt.target.Name2 // worked
// just say i = 1
i=1;
arraygrid.push({Name:this["evt.target.Name"+i],
Test:this.["evt.target.Test"+i]}); // error
//or
arraygrid.push({Name:this["Name"+i],
Test:this.["Test"+i]}); // error too
// eval() noexistent, set() didn't worked on actions frame panel
//?????
}
};
I hope it's very clear.
You could use this[varName] if I understand your question right.
So if varName is a variable containing a string which should be a variables name, you could set and read that variable like this:
this[varName] = "someValue";
trace(this[varName]);
Update:
In your example, you could try: evt.target["Test"+i] instead of Test:this.["evt.target.Test"+i]
If you have a set of strings that you'd like to associate with values, the standard AS3 approach is to use an object as a hash table:
var o = {}
o["test1"] = 7
o["test2"] = "fish"
print(o["test1"])