Tutorials, extensions, and source files for ActionScript, Flash, and other Adobe products.


senocular.com ActionScript Library


Name: extractNumbers() - extracts numbers from a string, returns either the nums or the string w/o them
Author: senocular: www.senocular.com
Date: 1899-12-31T00:24:36.300
String EXTRACTNUMBERS: returns either all number
occurrences or non-number occurrences within a string.
- returnType: (optional) if a non-number the return string will be the characters of the
original string without any numbers.  If a number (or a string of numbers) the return value will
be a number of all the number digits within the string.  If an empty string is passed,
a non-number character string will be returned. Default is numerical.
- Returns the original string either lacking or containing only its numerical characters.  If
returned as a number, it will be returned as a Number object. (if you dont like it being a
Number object you can replace return (t) ? r : Number(r); with just return r;)

myString = "abc123defghi456789jkl";

extractNums = myString.extractNumbers(); // default, nothing passed
trace(extractNums); // traces 123456789

myStringNums = myString.extractNumbers(1); // a number passed
myStringChars = myString.extractNumbers("a"); // a nonNumber passed
trace(myStringNums); // traces 123456789
trace(myStringChars); // traces abcdefghijkl

String.prototype.extractNumbers = function(returnType){
	var i, l = this.length, t = isNaN(returnType), r = "";
	for (i=0; i<l; i++) if (isNaN(this.charAt(i)) == t) r += this.charAt(i);
	return (t) ? r : Number(r);