Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




String Functions



I need to create an ascending array of numbers each formatted with 4 digits 0000000100020003 up to say 0040 what is the most elegant/efficient way of achieving this ? Are there any flash formatting functions that I could use?



KirupaForum > Flash > ActionScript 1.0/2.0
Posted on: 01-30-2006, 07:28 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

3 Useful String Functions...
Search and Replace

Code:
function searchandreplace(the_string, search_string, replace_string) {
var pos = 1;
while (pos <= the_string.length) {
start_string = substring(the_string, 1, pos-1);
check_string = substring(the_string, pos, length search_string));
end_string = substring(the_string, pos+length(search_string), length(the_string));
if (check_string == search_string) {
the_string = start_string + replace_string + end_string;
}
pos++;
}
return the_string;
}

Example:
var something_to_say = searchandreplace('nothing to say', 'nothing', 'something');
Trim String

Code:
function trimstring(the_string, characters, from_start, from_end) {
if (from_start == true) {
while (characters == the_string.substring(0, characters.length)) {
the_string = the_string.substring(characters.length);
}
}
if (from_end == true) {
while (characters == the_string.substring(the_string.length-characters.length)) {
the_string = the_string.substring(0, the_string.length-characters.length);
}
}
return the_string;
}

Example:
var shorten_it = trimstring('...hello...', '.', true, true);
Trim Lines (requires trimstring function)

Code:
function trimlines(the_string, characters, from_start, from_end) {
var lines = the_string.split(Newline);
for (var n in lines) {
lines[n] = trimstring(lines[n], characters, from_start, from_end);
}
the_string = lines.join(Newline);
return the_string;
}

Example:
(This function is most useful when you are loading a text file with several
lines and want to trim the spaces from the front and end of each line.)
var trimmedfile = trimlines(*some text from a file*, ' ', true, true);

Advanced Example:
Suppose I have the following XML file:

Code:
<TOPNODE>
<MOREDATA>Yes!</MOREDATA>
</TOPNODE>
For those who have played around with the XML capabilities in Flash, you will realize that Flash 5 does not like those Newlines and spaces. So what do you do to keep your XML file formatted with linebreaks and leading spaces, your XML object in Flash 5 like you expect it, and save yourself from having to write a Perl or PHP script to make the necessary conversions? Try something like this:


Code:
//upload XML file
myxml = new XML();
myxml.load('somefile.xml');
myxml.onLoad = properXML;

function properXML() {
//convert myxml to string, take out leading and trailing spaces
myxml = trimlines(myxml.toString(), ' ', true, true);
//take out Newlines
myxml = searchandreplace(myxml, Newline, '');
//convert back to XML
myxml = new XML(myxml);
}
Disclaimer:
Be careful how you use the above example if you have an XML file that contains node values that are supposed to have linebreaks.

Conclusion:
I hope these functions will save you some time in your development. Please drop me a line if you would like me to write up a tutorial or post a source file to Flashkit. (I do have limited time, but if I get enough responses, I'll find the time to do it.)

Happy Flashing :-)

Kaptain Kory
[Edited by kaptainkory on 11-04-2000 at 01:41 PM]

String Functions?
are their any strinfg functions in flash? for example i have a string variable and i want to know the length of the string. also is there a way to tell if a variable is empty?

Thanks in advance!

New String Functions Tell Me What You Need
I am writing an extention to the String class, which includes all the methods of the original String class.

ex. charAt() charCodeAt() fromCharCode(), slice(), etc...

i am adding more methods to make manipulating strings in flash a breeze.

here are the methods i have working now.

charOccurCount(ch);
returns a count of occurances of a specified character.
note: if your string is longer than 1 character this will return -1;

convert_stringToHex()
returns a hex encoded string.

genUniqSuffix(prefix)
returns a guaranteed uniq suffix to fix your cache problems.
prefix defaults to "?uniq=" so you dont need to include the argument.

replaceWithArray(ary, rs)
returns a string after replacing a specified string with elements in an array
ex.


ActionScript Code:
var s:XString = new XString("Michael is .::. because he never saw a .::. before .::.");
trace(s.replaceWithArray(new Array("amazed", "dog", "today"), ".::."));

traces this...

Michael is amazed because he never saw a dog before today

shiftCharCode(n)
returns string;
n is a number that will be added to the charCode of each character.

ex. if your string is "abcd" and you use shiftCharCode(1) then your returned string will be "bcde"

trimEnds()
returns string;
this cuts away all white space before and after you string.
ex. your string is " trim me ", then your return string will be "trim me"

trimL()
returns string;
trims all white space before string

trimR()
returns string;
trims all white space after string

validateEmail()
returns Boolean;
first runs trimEnds() and then checks string for certain requirements like having 1 '@' char, and having a domain name of at least 3 chars, and a suffix of at least 2 chars, and that the first char in the string is not the '@'

ex. a@abc.tv will return true
@abc.tv will return false
a@ab.tv will return false
a@abc.t will return false;

chad.fon@domain.net is supported, will return true

I KNOW there is more needed, if you have any needs for parsing strings in a certain way then let me know, i want to build this thing up.

String Validation Functions?
I need some string validation functions...
Does anyone have such functions that I could borrow?
[I promise to give them back.] : )

I need functions to validate email addresses, telephone numbers and names.

Any help would really be appreciated.

Thanks.


Jam

String Functions For Flash
I have worked on a .as file containing string functions for a few days just going over it to see if it is all optimized...

Function List:
-rot_13
-str_shuffle
-str_ipos
-str_ireplace
-str_pad
-str_parse
-str_pos
-str_replace
-str_slash
-substr_replace

I am still wondering if it is perfectly optimized for all parts or if there is room for any improvement. So I need some people here willing to check it out...

You can check out the beta here: http://www.cubedstudios.com/String_Functions.as

-----Soccr743-----

PS: If you plan to use this script in any flash project give credit when you can

Library Of String Functions
Has anyone got a library or Class extension for string processing?

For example:

string.word(n) -- find nth word delimited by spaces
string.line(n) -- find nth line of text delimited by <cr>
string.item(n) -- find nth item delimited by commas

etc

(You know, most of the MM Director etc string methods)

If not: side question - can you EXTEND the String.as Class even though it is INTRINSIC ?


Thanks.

Extending String Functions
More OOP woes...
Here is what I want to do...extend the String class

Code:
class example extends String {}
and then I want to take things that are already strings and add a function to them which goes through and removes & and turns it back to & am things got some test code for that here
Code:
function htmlToString():Void {
var args:Array = new Array();
args = this.split("&");
this = args.join("&");
args = this.split("&apos;");
this = args.join("'");
args = this.split(""");
this = args.join('"');
args = this.split("<");
this = args.join('<');
args = this.split(">");
this = args.join('>');
}
But when I go and compile it I get error msg's like this
Quote:





Originally Posted by compiler


Line 13: Type mismatch in assignment statement: found String where htmlString is required.
this = args.join('>');

String Replace Functions
Per another user's request...(this was previously posted in the Flash 8 area)...
And I have [updated], tested and confirmed that replaceMultiple will work correctly. ( i discovered a misspelling in the previous version).

i have also included method speed information, for those nuts (like myself) that are concerned about processing speed.

replace is recursive, so it is considered Order 1 (uber fast)
replaceMutiple is a single loop, considered Order n (a little slower--but if you're working with a fixed set of data, you're good to go!)


Code:
/**
* I took out the original version of this function i posted because I realized the snippets sticky had a better way to do this. (plus, this is easier to read)
* this version, however, assumes you want the actual String prototype to modify its contents -- use as needed
* @param String search
* @param String replace
* @return String
*/
String.prototype.replace = function(search:String, replace:String):String {
this = this.split(search).join(replace);
return this;
}

/**
* Replaces characters within a string
* replace(Array, string|char)
* Method Speed: n
* @param Array instances
* @param String|char replacement
* @return string
*/
String.prototype.replaceMultiple = function(instances, replacement) {
for(i=0;i<instances.length;i++)
this = this.replace(instances[i],replacement);
return this;
}

don't forget these depend on some code found in the Kirupa tutorial 'bestof_search' which scans XML files

Code:
/*
* contains()
* @param String
* @return int
*/
String.prototype.contains = function(searchString){
return (this.indexOf(searchString) != -1);
}
/**
* contains()
* @param String searchvalue
* @return bool
*/
Array.prototype.contains = function(searchValue){
var i = this.length;
while(i--) if (this[i] == searchValue) return true;
return false;
}

with the aforementioned code and the code below, you can build a tiny xml search engine...which i am currently developing for an application


Code:
/**
* GetKeyWords()
* Method Speed: Order n
* Method Type: loop
* @param String query
* @return String[]
*/
GetKeyWords = function(query) {
var keys= [];
// the next two lines could be combined, but it's just too hard to read; so they're split up like good like codelings
query = query.replaceMultiple(punctuation,' '); // spaces are our delimiter, (this could be customized in the method signature, but I don't think it would be any easier to use
var captured = query.toLowerCase().split(' '); // and as such, we will use them to break up our query into keywords
for(i=0;i<captured.length;i++)
if(!isIgnoredWord(captured[i], ignoredWords)) keys.push(captured[i]);
return keys;
}
/**
* isIgnoredWord(str, array)
* Method Speed: Order 1
* @param String str
* @param Array wordList
* @return bool
*/
isIgnoredWord = function(str, wordList) {
if(str.length<3) return true;
return wordList.contains(str.toLowerCase());
}

Extending String Functions
More OOP woes...
Here is what I want to do...extend the String class

Code:
class example extends String {}
and then I want to take things that are already strings and add a function to them which goes through and removes & and turns it back to & am things got some test code for that here
Code:
function htmlToString():Void {
var args:Array = new Array();
args = this.split("&");
this = args.join("&");
args = this.split("&apos;");
this = args.join("'");
args = this.split(""");
this = args.join('"');
args = this.split("<");
this = args.join('<');
args = this.split(">");
this = args.join('>');
}
But when I go and compile it I get error msg's like this
Quote:





Originally Posted by compiler


Line 13: Type mismatch in assignment statement: found String where htmlString is required.
this = args.join('>');

Made Functions Using For Loop, Trace Returns Undefined When Running Functions?
ActionScript Code:
var navAreas:Array = new Array("LOL", "WOOT", "ROFL");for (var f:Number = 0; f < navAreas.length; f++) {    this["action" + f] = function () {        trace(navAreas[f]);    };        // should make functions action0, action1, action2.}action1(); // shou'd return WOOT, but returns undefined.  

Dynamic Functions - Creating Functions At Runtime Without So Many Ifs/elses...
Hi, nice to register after lurking for a while and seeing how smart people are on here......

I am writing some code that needs to be very efficient, yet flexible. This is in a class and when the class gets initialized a function is setup. I want this function to run straight through without doing any time-consuming things such as calling other functions or routines, or doing any if/else logic/branching.

Now I know that you can setup a function at anytime during runtime such as:


Code:
var myFunction:Function = function() {trace('HELLO!')}
But what I am trying to do is to try and append code to a function based on logic, yet I don't want the function to be deciding this logic when it is running as it will only need deciding when the function is created.... imagine if it were a string it would be something like myFunction+="do somethingelse;" which would be the same as having initially setup myFunction as such:


Code:
var myFunction = function() {do something; do somethingelse;}
With this I seem to be having no luck

Here's an example where I setup the most compact/efficient function at runtime depending on what I want the function to do. Now this was fairly simple because when we create the function there are only a few possible variations, but I need someway of doing a function+= as my real code has quite a few variations and it would be a nightmare have a zillion if/else branches. REMEMBER I do not want any logic/decisions in the function itself as it to be the most efficient the function must be as compact as possible and run straight-through.


Code:
var dynamicFunction:Function;
//
// Setup the dynamic function & call it
// In this example outputs "Hello Jim" & "Goodbye Jim"
dynamicFunction = CrapSetupRoutine(true, true, "Jim");
dynamicFunction();
//
// Try and setup the dynamic function using a less ify/elsey (less complicated) routine & call it
// In this example it doesn't work if we try and make it say both Hello & Goodbye like above :(
dynamicFunction = SetupRoutineIWouldLike(true, true, "Jim");
dynamicFunction();
//
function CrapSetupRoutine(sayHello:Boolean, sayGoodbye:Boolean, yourName:String):Function {
var returnFunction:Function;
// Far too many ifs/elses...but remember the function created cannot have any if/else logic or calls to other functions
if (!sayHello and !sayGoodbye) {
returnFunction = function () {
trace("<dynamicFunction> sits bored");
};
} else if (sayHello and sayGoodbye) {
returnFunction = function () {
trace("Hello "+yourName);
trace("Goodbye "+yourName);
};
} else {
if (sayHello) {
returnFunction = function () {
trace("Hello "+yourName);
};
} else {
returnFunction = function () {
trace("Goodbye "+yourName);
};
}
}
return returnFunction;
}
//
//What I actually want the Setup function to resemble is this
function SetupRoutineIWouldLike(sayHello:Boolean, sayGoodbye:Boolean, yourName:String):Function {
var returnFunction:Function;
// the ifs/elses are as minimal as possible, which is good
if (!sayHello and !sayGoodbye) {
returnFunction = function () {
trace("<dynamicFunction> sits bored");
};
} else {
if (sayHello) {
returnFunction = function () {
trace("Hello "+yourName);
};
}
if (sayGoodbye) {
// the += below doesn't work.....so the question is how to append to it?????
returnFunction += function () {
trace("Goodbye "+yourName);
};
}
}
return returnFunction;
}
// The end
P.S. I knew the += would never work as this is a function and not a string. But at least if you think of the function as a string you'll get what I'm trying to do.....I suspect if it can be done it involves casting or something and maybe using strings initially??

Error 2101: The String Passed To UrlVariables.decode() Must Be Url-encoded Query String
I am trying to make a flash contact form which will submit the firstname, lastname, email and comments to an asp.net page.

I am have having the following error:

Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs

I am using the following action script code as pasted below. This action script is communicating with an asp.net file to send the email out. In the end it responds back with response=passed or failed.

I have already spent around 3 hours figuring it out.. and looking through the internet for resolution but no luck. Any help will be appreciated.

stop();
submit_btn.addEventListener(MouseEvent.CLICK, submit);

function submit(e:MouseEvent):void
{
var variables:URLVariables = new URLVariables();
variables.firstname = firstname_txt.text;
variables.lastname = lastname_txt.text;
variables.email = email_txt.text;
variables.comments2 = comments_txt.text;

var req:URLRequest = new URLRequest(”emailacount.aspx”);
req.method = URLRequestMethod.POST;
req.data = variables;

var loader:URLLoader = new URLLoader();
loader.dataFormat = URLLoaderDataFormat.VARIABLES;
loader.addEventListener(Event.COMPLETE, sent);
loader.addEventListener(IOErrorEvent.IO_ERROR, error);
loader.load(req);

status_txt.text = “Sending…”;

}

function sent(e:Event):void
{
status_txt.text = “Your email has been sent.”;
firstname_txt.text = “”;
lastname_txt.text = “”;
email_txt.text = “”;
comments_txt.text = “”;
}

function error(e:IOErrorEvent):void
{
status_txt.text = “There was an error. Please try again later.”;
}

and the following asp.net code:

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Net.Mail" %>
<script language="VB" runat="server">
Sub Page_Load(Sender As Object, E As EventArgs)
Try
Dim fromEmailAddress = "paul@lancierinc.com"
Dim toEmailAddress = "rizwandar@gmail.com"

Dim firstName = Request.QueryString("firstname_txt")
Dim lastName = Request.QueryString("lastname_txt")
Dim comments = Request.QueryString("comments_txt")
Dim userEmail = Request.QueryString("email_txt")

'create the mail message
Dim mail As New MailMessage()

'set the addresses
mail.From = New MailAddress(fromEmailAddress)
mail.To.Add(toEmailAddress)

'set the content
mail.Subject = "Email from" & firstName & " " & lastName
mail.IsBodyHtml = True
Dim strBody As String = "<b>Email from</b>" & " " & firstName & " " & lastName & "<br><b>Email Address:</b> " & userEmail & "<br><b>Comments:</b> " & comments
mail.Body = strBody

'send the message
Dim smtp As New SmtpClient("mail.lancierinc.com")
smtp.Send(mail)
Dim urltoencodestring2 = "response=passed&err=0"
'Response.Write(urltoencodestring2)


Catch smtpEx As SmtpException
'A problem occurred when sending the email message
'ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a problem in sending the email: {0}');", smtpEx.Message.Replace("'", "'")), True)
Response.Write(smtpEx.Message)
Dim urltoencodestring = "response=failed&err=1"
'Response.Write(urltoencodestring)

Catch generalEx As Exception
'Some other problem occurred
'ClientScript.RegisterStartupScript(Me.GetType(), "OhCrap", String.Format("alert('There was a general problem: {0}');", generalEx.Message.Replace("'", "'")), True)
Dim urltoencodestring3 = "response=failed&err=1"
'Response.Write(urltoencodestring3)
End Try
End Sub
</script>

String Passed To URLVariables.decode() Must Be A URL-encoded Query String...
I really don't understand why this won't work? I've made a test which sends some POST data to a script on my page which works fine. But why does not this work?


Code:
var mapsize = _cmap.fieldx.toString(16) + _cmap.fieldy.toString(16);
var names = "Zomis_AI6";
var description = "descr";
var result = "gameresult";
var upldata: String = "mapsize="+mapsize+"&names="+names+"&description="+description+"&result="+result;
trace(upldata);
var variables:URLVariables = new URLVariables(upldata);
var request2:URLRequest = new URLRequest();
request2.url = "http://www.zomis.net/record.php";
request2.method = URLRequestMethod.POST;
request2.data = variables;
var loader2:URLLoader = new URLLoader();
loader2.dataFormat = URLLoaderDataFormat.VARIABLES;
loader2.addEventListener(Event.COMPLETE, uploadcomplete);
try {
loader2.load(request2);
trace("Loaded");
}
catch (error:Error) {
trace("Unable to load URL");
}
Tracing gets:

Code:
mapsize=1010&names=Zomis_AI6&description=descr&result=gameresult
Loaded
Error: Error #2101: The String passed to URLVariables.decode() must be a URL-encoded query string containing name/value pairs.
at Error$/throwError()
at flash.net::URLVariables/decode()
at flash.net::URLVariables$iinit()
at flash.net::URLLoader/flash.net:URLLoader::onComplete()

Multiple Functions Or Long Functions With For.. Statements?
Which is better? A long function with a couple of for... statements, or multiple functions with only one for... statement in it?

Andy

Class Functions Not Able To See Other Member Functions/variables?
I am having a problem which has crept up on me a few times now. I am trying to call another member function within the same class, but Flash is unable to recognize it. This also happens when I try to read values of come variables.

For example, here I am trying to set the private boolean member variable to the state of the checkbox.

//NOTE: This is an EventListener. Does this change something major?

private function CheckBoxClick( evt )
{
_enabled = _root["test_sp"].content[_checkBoxName].selected;
trace( _checkBoxName + " checked: " + _root["test_sp"].content[_checkBoxName]._y );
}

This will output the following: "undefined checked: undefined"

Now in the function directly above it, I have the following function:

public function SetYPosition(pos:Number)
{
trace( _checkBoxName );
_root["test_sp"].content[_checkBoxName]._y = pos;
}

And this function will correctly output the checkbox name as well as update the position.

If I try adding the function call "SetYPosition(500);" to the first function (CheckBoxClick), the function will never be called as if Flash cannot see it.

In the past I have avoided this by using the global instance of the class such as _global.settings.function(blah), but the class I am working on now does not have a global instance.

Any ideas? This is really annoying!

Thanks!!!































Edited: 06/27/2007 at 03:30:12 PM by JoMasta

Randomize String And Create Textfields With String Txts
Hi,
is there some easy method to randomize elements of an array (to randomize index numbers) and create textfields with name of these elements ?
I had no problem making a photo gallery with strings but now I have to do a menu , with spacing (there should be same space between all the words of an array generated textfields)...How can this be accomplished ?Thanx in advance, Meerah

Convert Multiline String To A One Line String With RegExp
better get my own thread for that

How can I convert a multiline String to a one line String?
EX:

PHP Code:




Testing is always full of man made bugs.
<a href="http://www.betterthannothing.com" title="betterthannothing" target="_blank">
  <font color="#22229C">Believe</font>
</a>
me when times comes that you have to
<a href="http://www.vreate.com" target="_blank">create</a>
useless stuff to test some other useless stuff to have
<a href="http://www.vreate.com">some</a>
real results.. its a pain.
<img src="http://www.markval.com/deerPack.jpg" height="484" width="352"/>
<em>Got to try that stuff to eventually love it one day.</em>






and should result in

Code:
Testing is always full of man made bugs.<a href="http://www.betterthannothing.com" title="betterthannothing" target="_blank"> <font color="#22229C">Believe</font></a>me when times comes that you have to<a href="http://www.vreate.com" target="_blank">create</a>useless stuff to test some other useless stuff to have<a href="http://www.vreate.com">some</a>real results.. its a pain.<img src="http://www.markval.com/deerPack.jpg" height="484" width="352"/><em>Got to try that stuff to eventually love it one day.</em>


I think it have to play with the ^ (caret) and m (multiline) ... just need to put the puzzle together.

String.as (Fishing Line Or Kite String)
Hello everyone. After reading the article on Glen Rhodes (Proud Canadian) I was wondering exactly how to insert the string.as file. I have been having huuuuuuge speed issues with my code. My file sizes are quite small (40 - 60 k)but they are very sluggish.

Thank you......
Please help


http://www.moodvibe.com

Trouble With String.indexOf And String.lastIndexOf
Hi,

I have an input text field used for time. I'm trying to set it up so the user has to enter a valid time into the box.

I set the box to be only 5 characters in length and to only use numbers and the ":" character.

I thought this code would insure there wouldn't be two ":" characters and the ":" would be at lease one character from the begining and at least two from the end.

But the if you enter 2:321 it comes back as a valid time.

Thanks in advance,
thurston


Code:
if(string.indexOf(":", 1) == string.lastIndexOf(":", string.length-3) ){
trace("Valid Time");
}else{
trace("Invalid Time!!!");
}

Changing A String Name In A Loop / Concatonating String Name?
Hey all,

Does anybody know of a way to change a string name as a loop proceeds?

This is the main piece of code that I wish to loop with i incrementing, so that whilst i=0 then:

_root.barARed._visible=barRed[i];
_root.barARed._width=barLength[i];
_root.barAYellow._visible=barYellow[i];
_root.barAYellow._width=barLength[i];
_root.barAGreen._visible=barGreen[i];
_root.barAGreen._width=barLength[i];
infoA.text=info[i];

and i=2 then:

_root.barBRed._visible=barRed[i];
_root.barBRed._width=barLength[i];
_root.barBYellow._visible=barYellow[i];
_root.barBYellow._width=barLength[i];
_root.barBGreen._visible=barGreen[i];
_root.barBGreen._width=barLength[i];
infoB.text=info[i];

and so on...I would use _root.barRedInstanceName[i]._visible=barRed[i]; but I can't give the movie clip (the bar) an instance name such as redBar[1], redBar[2] etc. (system reserved I'm told)

I guess what I am trying to ask in a roundabout way: is how do you concatonate the name, rather than the contents of a string?

Hope you'll forgive me if this is something really simple that I am overlooking, but I only have a very short experience of flash.

Thanks

Al

Ball Bouncing On String: Getting The String To Be Bigger?
I have a black line which is simply a movie clip and a yellow circle which is also a movie script. The ball works great, it bounces on the bottom of the movie, and you can pick it up and throw it around. So now I want to attach the ball to the black line. So:

1. How can I make it so that the top part of the line will stay in one position, and so that a bottom part of it will move around? Is there any way I can link the two at a certain point so that wherever the ball goes the line will stay attached to it at that point?

2. In an attempt to try and reach this point I came up with this script in the ball for when it is not being dragged anywhere. The most important bit is really the bottom:


ActionScript Code:
} else {
        old.x = pos.x;
        old.y = pos.y;
        pos.x = _x;
        pos.y = _y;
        vel.x = (pos.x-old.x)*2;
        vel.y = (pos.y-old.y)*2;
        //Finds the change in position and adds that as an extention to the line:
        _root.ballstring.height += (old.y - pos.y);

Anyone reckon they could help me out? Thanks!

Keeping A String A String With Dynamic Text
I've got some dynamic text (from MYSQL & ColdFusion) that needs to be kept as a string and is (i think) being converted into a number.

The recordset is returning 8'6" (eight feet, six inches)

and my dyn text box displays 86.

Anyway around this from within Flash? I know you can strict data type in AS 2.0 but no chance of migrating this project to 2.0!

What's The Best Way To Parse Out A Url String Using The String Object In Flash
I'm creating a CMS(Content Management System) tool so that users can change text and the changes be reflected in a text window in flash . The text that the user enters in the CMS tool will be stored in the database.

In flash I want to parse the string that I get from the database and look for URL strings that start with http "http://www.someurl.com" and parse out that substring.

For example the string could be "Please vist my site at http://www.site.com". I would want to parse out the http://www.site.com


If I find this url string I want to pre-pend the a href tag <a> and append the closing </a> tag to the string so that this link will be clickable from the textfield.

Does flash have an object that deals with Regular Expressions?
I've looked at the String object in flash but not sure how to achieve this task

I'm currently working on this so any ideas?

Convert Html String To Xhtml String
Anyone know of a great way to convert an html string format from flash into a resembalnce of xhtml for outputing to a server or a direction i could go in to do this.

Thanks

Randomize String And Create Textfields With String
Hi,
is there some easy method to randomize elements of an array (to randomize index numbers) and create textfields with name of these elements ?
I had no problem making a photo gallery with strings but now I have to do a menu , with spacing (there should be same space between all the words of an array generated textfields)...How can this be accomplished ?Thanx in advance, Meerah

Pass A String, Return Object With Name String
I feel like this should be pretty easy, but I 'm not quite sure how to do this...

I've got a string that is the name of a movieclip which is on the stage. I'd like to write a function which I can pass that string and have it return the object which has the instance name of that string.

Any hints?

Thanks.

John

What's The Best Way To Parse Out A Url String Using The String Object In Flash
I'm creating a CMS(Content Management System) tool so that users can change text and the changes be reflected in a text window in flash . The text that the user enters in the CMS tool will be stored in the database.

In flash I want to parse the string that I get from the database and look for URL strings that start with http "http://www.someurl.com" and parse out that substring.

For example the string could be "Please vist my site at http://www.site.com". I would want to parse out the http://www.site.com


If I find this url string I want to pre-pend the a href tag <a> and append the closing </a> tag to the string so that this link will be clickable from the textfield.

Does flash have an object that deals with Regular Expressions?
I've looked at the String object in flash but not sure how to achieve this task

I'm currently working on this so any ideas?

Convert Html String To Xhtml String
Anyone know of a great way to convert an html string format from flash into a resembalnce of xhtml for outputing to a server or a direction i could go in to do this.

Thanks

Randomize String And Create Textfields With String
Hi,
is there some easy method to randomize elements of an array (to randomize index numbers) and create textfields with name of these elements ?
I had no problem making a photo gallery with strings but now I have to do a menu , with spacing (there should be same space between all the words of an array generated textfields)...How can this be accomplished ?Thanx in advance, Meerah

Complex String.split And String.substring
Hey, Im an actionscript newbie and am having a little tourble with a string.

I have a string variable containing the value:

myString = "Johnny Lewis, Danny Lopez, Alex Prince, Sandro Lee, Nick Salvage"

What I want to do is trim their last name so it only shows their first initial, so it would be converted to:

myStringTrimmed = "Johnny L, Danny L, Alex P, Sandro L, Nick S"

So im guessing I need to split it by the commas, then split those again by the blank space.

The only problem is that this variable will be dynamic and the number of people in the variable will always be different. Sometimes there will only be one name, sometimes as many as five.

Any help would be much appreciated.

String = String + If(string.length) ... + String
A few languages have an IIf() statement, which works like the if statement, but is good for use inside of strings.

Flash 8 apparently doesn't have it, but I tried something similar to this..


Code:
_global.mStruct.mString = "My first name is " +
mf.text + if(mi.text.length > 0) { ". My middle initial is " + mi.text} +
". My last name is " + ml.text + "."
And I get

"Operator '+' must be followed by an operand", referring to the red + above.

Is there a way to do this, or do I need to just break into seperate if statements and appending the value to the value of the textbox?

Thanks for any help.

[F8] Running Functions From Within Functions In A Class
For some reason, whenever I try to run a private function from within another private function in a class, it doesn't work.


Code:
private function getVars(theVar) {
switch (theVar) {
case "m" :
return this.m;
break;
case "nI" :
return this.nI;
break;
case "rX" :
return this.rX;
break;
case "rY" :
return this.rY;
break;
case "cX" :
return this.cX;
break;
case "cY" :
return this.cY;
break;
case "s" :
return this.s;
break;
case "a" :
return this.a;
break;
default :
return "";
}
}



Code:
private function cSpeed():Void {
// ccX is just a placeholder for the cX variable
// so that the function can use it.
var ccX:Number = cX;
m.onMouseMove = function() {
s = (this._xmouse-ccX)/1500;
getVars("m");
}
}


I just used getVars("m") for the hell of it...just to see if it would work...but it didn't. Any idea why not?

[F8] Calling Functions Within OnEvent Functions.
Ive just stumbled upon an annoying problem, Im writing a custom class which, in its constructor attaches a movie clip to a main one (passed in as a parameter).
this all works fine.
My problem arises when i try to, also in the constructor, create an onRollOver event on the movieclip i attached earlier (its stored in a field).

The onRollOver event works fine, calling the trace statement ive been using, but it won't call any function which i ask for.


this is the code where im having issues:


Code:

function Corner(xPosition:Number, yPosition:Number, circ:Circle, deep:Number, baseClip:MovieClip)
{
this.image = baseClip.attachMovie("Corner","CornerX",deep);
this.image._x = xPosition;
this.xPos = xPosition;
this.image._y = yPosition;
this.yPos = yPosition;

this.circle = circ;

this.image.onRollOver = function()
{
trace("debugOne"); //this trace statement works fine

this.otherFunction(); //Problem is here, The code wont call this function for some reason
}

this.depth = deep;
}

function otherFunction()
{
trace("debugTwo");
}
any ideas why its not calling my function?

[F8] Functions Inside Functions? Urgent
Hi, is this in any way valid?


Code:
this.onRelease = function(){
_root.mainbutton(){
freeze == false;
}
i have a set of buttons id like to play their animations when i press a button. Can this be done?

Any help or pointers would be greatly appreciated, thanks!

Declaring Functions In Other Functions And Callbacks
Hi - I'm curious to know if the following situation is possible (I haven't gotten it to work yet).

I'd like to load a series of images, and in the callback, place them in different positions in my array. Instead of writing a separate callback for each image, I'd like to do something like the following:

But it looks like each version of the function gets the end version of "i", not the version of i that existed when the function was declared.

Is something like this at all possible?







Attach Code

public function loadImages():void
{
for (var i:int = 0; i < 4; i++)
{
function myCallback(e:Event):void
{
myArray[i] = Bitmap(e.target.loader.content);

}
loadImageWithCallback(image, myCallback);
}
}

Functions Passed As Arguments To Other Functions
FLASH MX 2004 - AS2.0

I have a function with 4 necessary arguments (aka parameters) in order to perform the actions. I would like to have the ability to pass the same function to itself as an argument (sort of like a recursive function) along with its arguments. Basically I want to "base" to engage an onMotionFinished event handler if there is another function passed as an argument. Something like...


PHP Code:



   function base (arg1, arg2, arg3 arg4, {arg5:another function, arg6:arg5s arg).....}){  //do the stuff  instructions = blahblahblah  if (arg5 is present){     instructions.onEventHandler = function(){         //perform function which is arg5...argN     }  } } 




Would there be a way to use listeners to do this or the AsBroadcaster? Thanks

How Can I Put A Number And A String Together So It Ends Up Being A String ?
How can I put a number and a string together so it ends up being a string ?


This doesn't work:
----------------------

somenumber=1;
somestring="File";

combination=somestring + somenumber;

----------------------

At the end i want to have this:

combination="File1";

Can anyone help ?

String Manipulation : Pad A String.length
hi,
i have an array of track/artist titles

_level0.trkList = [object #218, class 'Array'] [
0:[object #219, class 'Object'] {
label:"Jeff Beck - Space for the Papa",
data:"spacepapa.mp3",
__ID__:0
},
1:[object #220, class 'Object'] {
label:"Jeff Beck - Another Place",
data:"anotherplace.mp3",
__ID__:1
},

i wish to add the array to a track info listbox component,
in such a way that the individual items in the array are
padded with spaces -" ", so as the length of the shortest
string equals the length of the longest string,

my listbox output is now -
Jeff Beck - Space for the Papa| * from time array
Jeff Beck - Another Place| * from time array

by adding spaces i would like it to be-
Jeff Beck - Space for the Papa| * from time array
Jeff Beck - Another Place"""""""| * from time array

does anyone know how to do this ?

many thanks for any help,

LoadMovie - Target String Or Not String?
I'm trying to figure out what the major differences and/or uses for using a target as a string with double quotes or without quotes...

For example whats the difference between the following 2 lines?

1. loadMovie("products.swf",_root.dropZone);
2. loadMovie("products.swf","_root.dropZone");

I know the target in the second line is a string and the target in the first line is a MC object(?). Any other major uses for these 2 variations?

Can Trace String But Cannot Set String To Variable
Hi,

I am importing a some text values from a text file and then trying to pass this value via a function

I can TRACE the text value successfully but cannot set it to a variable.

************************************************** **************
function test(){
var aTestVariable

myData = new LoadVars()
myData.load("thenews.html")
myData.onLoad= function(success){

if(success){
trace(myData.Title); //THIS WORKS
aTestVariable = (myData.Title);
}
}
return aTestVariable
}

function testFunction() {
trace(test()); //THIS DOES NOT WORK!
}
************************************************** **************


Can someone please tell me what is wrong with this:


trace(myData.Title); //THIS WORKS
aTestVariable = (myData.Title);

HELP!

Rich

How Do I Insert A String Into The Middle Of Another String?
I'm going round and round in ciccles trying to figure out how to use the string functions.

All I want to do is insert a string into the middle of another one!

How do I do this?

Any help would be appreciated.

Thanks.


OM

Trouble Finding A String Is A String
I'm trying to find a certain string I provide in another string, I know that in JavaScript you can use indexOf to find it:

myString = "hello world";
findString = "world";
if(myString.indexOf(findString) >= 0) {
alert("found");
}

I tried that in flash (replacing alert with trace) and it doesn't work

can anyone help???

Can't Pass String To Nc.connect(string)
hey guys. fairly new to flash, but I've managed to throw together a player with info and tutorials from here and other places. I've got everything just how I want it save for one problem. I've got an XML file that I get the URL for my server from and also get the names of videos to populate a list. Here's the problem:
I can get the URL into a string in my program (it traces fine). However, when i try to pass that string in my nc.connect(string) it doesn't work. Everything loads fine, but when you click a video, it can't connect to it. If I manually enter the URL into the connect field like this: nc.connect("rtmp://url") it works fine.
So am I missing something? Why can it take the URL manually entered and not from a string?

Find A String In A String Chaine
Hi, I need a function that detects if a string was found inside another string:

here's an example:
string1 = "ABC"
string2 = "FGABCJHG"

in this case, the function would return true...
any ideas on how to make this? i m being lazy, i could try to do it by myself but sometimes this kind of functions were already made by someone and they are in internet or whatever.

thanks!

Need To Parse String But Not Literal String...
Once again I have run into something....

Here is the start of the code:
CODEvar target = this.onStage.allNotesOnStage.easyArray
var randomNum = Math.floor(Math.random() * (max - min + 1)) + min;
var showNote = target[randomNum];

Remove String (string Var - String Var )
hi guys ,
i need to remove a string to an other string

here a simple example


ActionScript Code:
var test1 = "test.allo255"
var test2 = "test.allo"
 
trace(test1)
trace(test2)
 
trace(eval(test1-test2))

i need to catch the number at the end

or remove the string part
(or even just a part , like if i can remove "test." and hang up with "allo255" its ok too)


here what i got ,

my output is

ActionScript Code:
_level0.my_sp.spContentHolder.img_mc5


i need to grab only "img_mc5" or only the # "5"

plz and a big tnx in advance

Save Object To String -> Load String And Convert Back To Object?
Wondering if anyone knows if this is possible. First a little explanation:

1. I have container grid where you can add and position MC's
2. The MC's x,y and other data is stored in a 3d object
3. The object is setup like this: matrix (object) -> levels (objects) -> profiles (objects). So basically a grid which mirrors what you see on screen.

This all works great; however, the application needs to have a save feature. My first thought was decode the matrix into an XML and save that.

Then I thought maybe you can just convert the matrix object to one big string and save that.

Questions: when the string is loaded back into the movie how do you (or can you even) covert it back in a object that flash can read?

Any help/input is greatly appreciated.

Functions Trough Functions...
Hi, I have some problems with relative/absolute functions...
The code is:

--------Main.fla:


Code:
import Bus;

var aBus:Bus=new Bus(wooz);

function wooz()
{
trace("wooz!!");
trace(this);
}

this.onMouseUp=function()
{
wooz();
}

wooz();
aBus.TryCallback();

---Bus.as



Code:
class Bus
{
var _couleur:String;
private var _Func:Function;

function Bus(Func:Function)
{
trace("exec func...");
_Func=Func;
}

function TryCallback()
{
_Func();
}
}
I would like to have an output like this:

wooz!!
_level0
wooz!!
_level0



...But i obtain this


wooz!!
_level0
wooz!!
[object Object]

I would like to keep _level0 as this, and not object, who aBus

Can U help me please???

thanks

Trace A Functions Name From Within Functions
I am setting up a series of function. I want to use the function name as a variable inside each function like this:

var thisFunction;

function functionName(){
thisFunction = this.name
trace(thisFunction)
}

I want to set funcName to the the name of the function, someName.
Thanks in advance!

Copyright 2005-08 www.BigResource.com, All rights reserved