Parsing a path in Actionscript 3? - actionscript-3

I'm using a URLLoader to load a photo and I want to be able to display the filename of the photo based on the URLLoader's loaderInfo.url property.
Given a loader named photoLoader, what the string called fileName be?

I would take the .url property and split it into an array using the / as the delimiter. Then just grab the last item in that array to get the filename.
Code:
var pathArray:Array = photoLoader.url.split('/')
var FileName:String = pathArray[pathArray.length()-1]

with
s:String = "http:/somedomain/someurl/somefilename";
You could do
fileName = s.split('/').pop()
to return the top of the array from splitting the url at '/'

var pathArray:Array = photoLoader.url.split('/')
var FileName:String = pathArray[pathArray.length-1]
Please note that the keyword "length" is not followed by parenthesis. For arrays, it is not supposed to be a function, it is a property. On the other hand, XML lists can use the length() function.

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

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;

How to declare a filled Vector?

I am using Vectors in Flash 10 for the first time, and I want to create it in the same way I used to do with Arrays, e.g:
var urlList : Array = [url1, url2, url3];
I have tried various different methods but none seem to work, and I have settled on the following as a solution:
var urlList : Vector.<String> = new Vector.<String>();
urlList.push(url1, url2, url3);
Is this even possible?
When it doubt, check the AS3 docs. :)
var urlList : Vector.<String> = new <String>["str1", "str2", "str3"];
trace(urlList);
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Vector.html#Vector()
Direct quote of the line I adapted this from in the documentation:
To create a pre-populated Vector instance, use the following syntax instead of using the parameters specified below:
// var v:Vector.<T> = new <T>[E0, ..., En-1 ,];
// For example:
var v:Vector.<int> = new <int>[0,1,2,];
You coerce an array to a Vector:
var urlList:Vector.<String> = Vector.<String>([url1, url2, url3]);

AS3 How to make a kind of array that index things based on a object? but not being strict like dictionary

How to make a kind of array that index things based on a object? but not being strict like dictionary.
What I mean:
var a:Object = {a:3};
var b:Object = {a:3};
var dict:Dictionary = new Dictionary();
dict[a] = 'value for a';
// now I want to get the value for the last assignment
var value = dict[b];
// value doesn't exits :s
How to make something like that. TO not be to heavy as a lot of data will be flowing there.
I have an idea to use the toString() method but I would have to make custom classes.. I would like something fast..
Why not make a special class that encapsulates an array, put methods in there to add and remove elements from the array, and then you could make a special method (maybe getValueByObject(), whatever makes sense). Then you could do:
var mySpecialArrayClass:MySpecialArrayClass = MySpecialArrayClass();
var a:Object = {a:3};
var b:Object = {a:3};
mySpecialArrayClass.addElement(a,'value for a');
var value = mySpecialArrayClass.getValueByObject(a);
I could probably cook up a simple example of such a class if you don't follow.
Update:
Would something like this help?
http://snipplr.com/view/6494/action-script-to-string-serialization-and-deserialization/
Update:
Could you use the === functionality? if you say
if ( object === object )
it compares the underlying memory address to see if two objects are the same reference...

Extracting "filename" from full path in actionscript 3

Does AS3 have a built in class / function to extract "filename" from a complete path. e.g. I wish to extract "filename.doc" from full path "C:\Documents and Settings\All Users\Desktop\filename.doc"
For Air, you can try using File Class to extract file name
var file:File=new File("path_string");
//path_string example "C:\\Windows\\myfile.txt"
var filename:String = file.name;
First you want to find the last occurrence of / or \ in the path, do that using this:
var fSlash: int = fullPath.lastIndexOf("/");
var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;
That will give you the index in the string that is right BEFORE that last slash. So then to return the portion of the string after that, you add one to the index (moving it past the last slash) and return the remainder of the string
var docName: String = fullPath.substr(slashIndex + 1);
To do this as a simple to use function, do this:
function getFileName(fullPath: String) : String
{
var fSlash: int = fullPath.lastIndexOf("/");
var bSlash: int = fullPath.lastIndexOf("\\"); // reason for the double slash is just to escape the slash so it doesn't escape the quote!!!
var slashIndex: int = fSlash > bSlash ? fSlash : bSlash;
return fullPath.substr(slashIndex + 1);
}
var fName: String = getFileName(myFullPath);
Couldn't you just do something basic like:
string filename = filename.substring(filename.lastIndexOf("\\") + 1)
I know it's not a single function call, but it should work just the same.
Edited based on #Bryan Grezeszak's comment.
Apparently you can use the File class, or more specifically, the File.separator static member if you're working with AIR. It should return "/" or "\", which you can plug in to #cmptrgeekken's suggestion.
Try this:
var file_ :File = new File("C:/Usea_/Dtop/sinim (1).jpg"); // or url variable ... whatever//
file_ = file_.parent;
trace(file_.url);
You can use something like this to do the job :
var tmpArray:Array<String>;
var fileName:String;
tmpArray = fullFilePath.split("\");
fileName = tmpArray.pop();
You have to take care if you are using Unix file system ("/") or Windows file system ("\").