I'm trying to find last character of a variable. My code is:
trace(this[String.fromCharCode(num) + i]);
I also need second character by backwards. Sorry for my English.
Edit:
I think I couldn't explain it exactly. I have some variables. One of them is: this["h5"]
I want it to return 5.
Is this what you're trying to do?
function lastNameChar(target:DisplayObject):String
{
return target.name.substr(target.name.length - 1, 1);
}
trace(lastNameChar(this["h5"])); // 5
You should be able to make use of a string's length and get characters of it using charAt.
So, if you had the following:
var myString : String = "abcdefg";
You could do this to get the last character:
myString.charAt(myString.length - 1); // (since the first character is at index 0
and to get the next to last character:
myString.charAt(myString.length - 2);
function getLastCharInString($s:String):String
{
return $s.substr($s.length-1,$s.length);
}
function getSecondLastCharInString($s:String):String
{
return $s.substr($s.length-2,$s.length);
}
Related
I am trying to remove specific characters from an array.
I am passing a sentence,characters from that sentence should be removed from alpha array using map() and filters(),
var alpha =['b','c','d','e','f','g','h','a']
function removeAlpha(sentence){
return alpha.map(function(melem,mpos,marr){
return sentence.toLowerCase().split("").filter(function(elem,pos,arr){
melem!=elem
});
});
}
console.log(removeAlpha('bdog'));
Please let me know ,what i am doing wrong
The inner callback function does not return a value. The melem!=elem should be return melem!=elem
After that correction the inner filter returns an array with one alpha letter removed from it, but only that letter. In the next iteration of the outer map, you start from scratch and return an array with only the second alpha letter removed, etc... This gives you an array of arrays, where in each array one of the alpha characters is removed.
Yet, you need something very different: you want the characters from the alpha array that are not in the sentence (instead of the characters of the sentence that are not in the alpha array).
For that you should apply the filter on alpha:
var alpha =['b','c','d','e','f','g','h','a']
function removeAlpha(sentence){
return alpha.filter(function(melem){
return !this.includes(melem);
}, sentence.toLowerCase());
}
console.log(removeAlpha('bdog'));
You can also use String#replace by converting the array to a string and use the sentence as a RegExp character set:
var alpha =['b','c','d','e','f','g','h','a'];
function removeAlpha(sentence){
return alpha
.join('')
.replace(new RegExp('[' + sentence + ']', 'g'), '')
.split(''); // replace all characters with an empty string
}
console.log(removeAlpha("bdog"));
I am attempting to apply a mask to another string to replace all wildcards in one string with the matching characters in the matching index while keeping the non-wildcard characters.
Eg:
starting string: "1234-234-3456-45-9876"
mask string: "____-___-0001-__-____"
when applied together: "1234-234-0001-45-9876"
Is this some usage of Regex I haven't seen before? I tried to understand the string.replace() type methods, but I don't think these apply.
Hope this will help you:
private function checkString():void
{
var starting:String = "1234-234-3456-45-9876";
var mask:String = "____-___-0001-__-____";
for(var i:int=0;i<starting.length;i++)
{
if(mask.charAt(i).match("[0-9]"))
{
starting = starting.substr(0,i) + mask.charAt(i) + starting.substr(i+1);
}
}
Alert.show(starting);
}
It will mask your string. Check result of alert.
This question relates to an animated map template which we have developed at the UKs Office for National Statistics. It has been applied to many datasets and geographies many uses without problem. For example,
http://www.ons.gov.uk/ons/interactive/vp3-census-map/index.html
http://www.statistica.md/pageview.php?l=ro&idc=390&id=3807
The .fla calls on a supporting .as file (see below) to introduce a thousand separator (in the UK a comma, in Germany a full stop (period) defined elsewhwere.
However, the dataset I am currently mapping has large negative values, and it tutrns out that the ORIGINAL HELPER FUNCTION below does not like negative values with 3, 6, 9 or 12 (etc) digits.
-100 to -999 for instance are rendered NaN,100 to NaN,999.
This is because such values are recognised as being 4 digits long. They are being split, the comma introduced, and the -ve sign is misunderstood.
I reckon the approach must be to use absolute values, add in the comma and then (for the negative values) add the -ve sign back in afterwards. But so far, trials of the ADAPTED HELPER FUNCTION have produced only error. :-(
Can anyone tell me how to put the -ve sign back in , please?
Many thanks.
Bruce Mitchell
==================================================================================
//ORIGINAL HELPER FUNCTION: ACCEPTS A NUMBER AND RETURNS A STRING WITH THOUSANDS SEPARATOR ATTACHED IF NECESSARY
function addThouSep(num) {
/*
a. Acquire the number - 'myTrendValue' or 'myDataValue' - from function calcValues
b. Record it (still as a number) to data precision.
1. Turn dataORtrend into a string
2. See if there is a decimal in it.
3. If there isn't, just run the normal addThouSep.
4. If there is, run addThouSep just on the first bit of the string - then add the decimal back on again at the end.
*/
var myNum:Number = correctFPE(num); // Create number variable myNum and populate it with 'num'
// (myTrendvalue or myData Value from calcValues function) passed thru 'correctPFE'
var strNum:String = myNum+""; // Create string version of the dataORtrend number - so instead of 63, you get '63'
var myArray = strNum.split("."); // Create array representing elements of strNum, split by decimal point.
//trace(myArray.length); // How long is the array?
if (myArray.length==1) { // Integer, no decimal.
if (strNum.length < 4)//999 doesn't need a comma.
return strNum;
return addThouSep(strNum.slice(0, -3))+xmlData.thouSep+strNum.slice(-3);
}
else { // Float, with decimal
if (myArray[0].length < 4)//999 doesn't need a comma
return strNum;
return (addThouSep(myArray[0].slice(0, -3))+xmlData.thouSep+myArray[0].slice(-3)+"."+myArray[1]);
}
}
==================================================================================
//ADAPTED HELPER FUNCTION: ACCEPTS A NUMBER AND RETURNS A STRING WITH THOUSANDS SEPARATOR ATTACHED IF NECESSARY
function addThouSep(num) {
/*
a. Acquire the number - 'myTrendValue' or 'myDataValue' - from function calcValues
b. Record it (still as a number) to data precision.
1. Turn dataORtrend into a string
2. See if there is a decimal in it.
3. If there isn't, just run the normal addThouSep.
4. If there is, run addThouSep just on the first bit of the string - then add the decimal back on again at the end.
*/
var myNum:Number = correctFPE(num); // Create number variable myNum and populate it with 'num'
// (myTrendvalue or myData Value from calcValues function) passed thru 'correctPFE'
var myAbsNum:Number = Math.abs(myNum); // ABSOLUTE value of myNum
var strNum:String = myAbsNum+""; // Create string version of the dataORtrend number - so instead of 63, you get '63'
var myArray = strNum.split("."); // Create array representing elements of strNum, split by decimal point.
//trace(myArray.length); // How long is the array?
if (myNum <0){ // negatives
if (myArray.length==1) { // Integer, no decimal.
if (strNum.length < 4)//999 doesn't need a comma.
return strNum;
return addThouSep(strNum.slice(0, -3))+xmlData.thouSep+strNum.slice(-3);
}
else { // Float, with decimal
if (myArray[0].length < 4)//999 doesn't need a comma
return strNum;
return (addThouSep(myArray[0].slice(0, -3))+xmlData.thouSep+myArray[0].slice(-3)+"."+myArray[1]);
}
}
else // positive
if (myArray.length==1) { // Integer, no decimal.
if (strNum.length < 4)//999 doesn't need a comma.
return strNum;
return addThouSep(strNum.slice(0, -3))+xmlData.thouSep+strNum.slice(-3);
}
else { // Float, with decimal
if (myArray[0].length < 4)//999 doesn't need a comma
return strNum;
return (addThouSep(myArray[0].slice(0, -3))+xmlData.thouSep+myArray[0].slice(-3)+"."+myArray[1]);
}
}
==================================================================================
If you're adding commas often (or need to support numbers with decimals) then you may want a highly optimized utility function and go with straightforward string manipulation:
public static function commaify( input:Number ):String
{
var split:Array = input.toString().split( '.' ),
front:String = split[0],
back:String = ( split.length > 1 ) ? "." + split[1] : null,
pos:int = input < 0 ? 2 : 1,
commas:int = Math.floor( (front.length - pos) / 3 ),
i:int = 1;
for ( ; i <= commas; i++ )
{
pos = front.length - (3 * i + i - 1);
front = front.slice( 0, pos ) + "," + front.slice( pos );
}
if ( back )
return front + back;
else
return front;
}
While less elegant it's stable and performant — you can find a comparison suite at my answer of a similar question https://stackoverflow.com/a/13410560/934195
Why not use something simple like this function I've made?
function numberFormat(input:Number):String
{
var base:String = input.toString();
base = base.split("").reverse().join("");
base = base.replace(/\d{3}(?=\d)/g, "$&,");
return base.split("").reverse().join("");
}
Tests:
trace( numberFormat(-100) ); // -100
trace( numberFormat(5000) ); // 5,000
trace( numberFormat(-85600) ); // -85,600
Explanation:
Convert the input number to a string.
Reverse it.
Use .replace() to find all occurrences of three numbers followed by another number. We use $&, as the replacement, which basically means take all of those occurences and replace it with the value we found, plus a comma.
Reverse the string again and return it.
Did you try using the built in Number formatting options that support localized number values:
Localized Formatting with NumberFormatter
How can i convert a type int into 8 digit hex decimal in flex
I need a function similiar in c# [ ToString("X8") ]. This function does the job in c#.
But what is the option in flex ?
As described in the docs, it's pretty much the same:
var myInt:int = 255;
var hex:String = myInt.toString(16);
trace(hex); //outputs "ff"
See http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/int.html#toString()
If it's colors you're after: the docs describe how to handle that case too.
There is however no built-in way to add the leading zeros. You can use a method like this one to do that:
public function pad(s:String, pattern:String="0", minChars:int=8):String {
while (s.length < minChars) s = pattern + s;
return s;
}
trace(pad(hex)); //000000ff
Note: this is for 6 digit hex colors but could easily be modified to any number of hex digits.
Found a lot of ways of outputting padded hex values that relied heavily on string padding.
I wasn't really happy with any of those so this is what I came up with: (as a bonus it fits on one line) You could even shorten it by removing the toUpperCase() call as case is really irrelevant.
"0x"+ (i+0x1000000).toString(16).substr(1,6).toUpperCase()
If you want to floor or ceiling that to black and white and put that in a function:
public static function toHexColor(i:Number):String {
return i<0 ? "0x000000" : i>0xFFFFFF ? "0xFFFFFF" : "0x"+ (i+0x1000000).toString(16).substr(1,6).toUpperCase() ;
}
Here is a more expanded version with comments:
public static function toHexColor(i:Number):String {
//enforce ceiling and floor
if(i>0xFFFFFF){ return "0xFFFFFF";}
if(i<0){return "0x000000";}
//add the "magic" number
i += 0x1000000;
//append the 0x and strip the extra 1
return "0x"+ i.toString(16).substr(1,6).toUpperCase();
}
This might be obvious to some people, but I have CSV data that I'm storing as a String in which every number is off by -1. I'd like to write a function (in ActionScript 3) in which I go in and increase every value by +1. How can I do this?
My CSV String looks like this:
public static const CSV_DATA:String = "14,15,16,8,9,8,9,8,9,8,9,264,265,266,267,268,269,8,9,260,261,262,263,8,9,1,2,3\n" +
"32,33,34,26,27,26,27,26,27,26,27,282,283,284,285,286,287,26,27,278,279,280,281,26,27,19,20,21\n" +
... etc
Thank you in advance.
In your case, just use String.split(). Primary split string by '\n', secondary split by ','. In result array every string with number process with parseInt function. After that, you can increase your numbers by one.
But if you need to read real CSV files, you can write class for this or use open-source
Here you go:
var CSV_DATA:String = "14,15,16,8,9,8,9,8,9,8,9,264,265,266,267,268,269,8,9,260,261,262,263,8,9,1,2,3,32,33,34,26,27,26,27,26,27,26,27,282,283,284,285,286,287,26,27,278,279,280,281,26,27,19,20,21";
var UPDATED_CSV_DATA:String = addOne(CSV_DATA);
function addOne(CSV:String):String
{
var CSVArr:Array = CSV.split(",");
for(var i=0;i<CSVArr.length;i++)
{
CSVArr[i] = Number(CSVArr[i]) + 1 ;
}
return CSVArr.toString();
}