Split if letters > at 10 in AS3 - actionscript-3

I'm trying to split every words that contains more than 10 letters.
How can I do ?
I did :
if (item.title.length > 10){
trace("item.length>10");
// What should I put here in order to erase the letters after the 10th one ?
}

if (item.title.length > 10){
trace("item.length>10"); // 0
trace(String(item.title).substring(0,10)); // if item.title is "star wars : the force" it will shows "star wars "
var arr:Array=String(item.title).split("");
for(var i:int=0;i<arr.length;i++)
{
trace(arr[i]);// it shows every letter in the array
}
}

var string0:String = 'hello';
var string1:String = 'hello this is a test string';
// trunkate to up to 10 chars...
string0 = string0.slice(0, 10);
string1 = string1.slice(0, 10);
trace('>' + string0 + '<'); // result is >hello<
trace('>' + string1 + '<'); // result is >hello this<

Related

Get an array of all Numbers inside a String

How can I get an array of all Numbers (if any) inside a String?
So that this:
var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));
Output this:
1,22,33,56,4,100,99
Regular Expressions is the answer you are looking for. You need something like that (not tested, yet the idea should be correct):
var source:String = "So 1 and 22 plus33 = (56) and be4 100 is 99!"
// The pattern \d+ instructs to find one or more consequent decimal digits.
// That also means that before each match there will be a non-digit character
// or the beginning of the text, and after the match will also be a non-digit
// or the end of the text.
// The [g]lobal flag is for searching multiple matches.
var re:RegExp = /\d+/g;
// Search for all the matches.
var result:Array = source.match(re);
Without the elaborate commenting the code could be reduced to this simple one-liner:
var result:Array = "So 1 and 22 plus33 = (56) and be4 100 is 99!".match(/\d+/g);
Please keep in mind that this search will return an Array of Strings so if you want them as ints you need to take some additional steps.
This is the working solution I have come up with:
function getNumAry(txt:String):Array {
var res:Array = new Array();
var str: String = ""
//Non-Number Chars to Dot
for (var i:int = 0; i < txt.length; i++) {
if(isNum(txt.substr(i,1))){
str += txt.substr(i, 1);
} else {
str += ".";
}
}
trace(txt);
trace(str);
//Spaces to Dot
str = str.split(" ").join(".")
trace(str);
//Dots to Single Dot
while (str.indexOf("..") != -1) {
str = str.split("..").join(".");
}
trace(str);
//Remove first Dot
if (str.indexOf(".") == 0 ) {
str = str.substr(1);
}
trace(str);
//Remove last Dot
if (str.lastIndexOf(".") == str.length-1 ) {
str = str.substr(0,str.length-1);
}
trace(str);
//get Nums if any
if (str != "" && str != ".") {
res = str.split(".");
}
return res;
}
function isNum(chr: String):Boolean {
return !isNaN(Number(chr));
}
if you run this:
var txt: String = "So 1 and 22 plus33 = (56) and be4 100 is 99!";
trace(getNumAry(txt));
This is the step-by-step trace of what you get:
So 1 and 22 plus33 = (56) and be4 100 is 99!
.. 1 ... 22 ....33 . .56. ... ..4 100 .. 99.
...1.....22.....33....56........4.100....99.
.1.22.33.56.4.100.99.
1.22.33.56.4.100.99.
1.22.33.56.4.100.99
1,22,33,56,4,100,99
Wondering if there has been an easier way?! :)

Convert JSON data to table

I am trying to create table from my JSON data which looks like this:
It works for a specific JSON data:
var items = [
{"Name":"A","Type":2,"Result":"0"},
{"Name":"A","Type":1,"Result":"1"},
{"Name":"B","Type":2,"Result":"1"},
{"Name":"B","Type":1,"Result":"0"},
]
But, it doesn't create table correctly if the columns ("Type") is random
var items = [
{"Name":"A","Type":5,"Result":"1"}
{"Name":"A","Type":2,"Result":"0"},
{"Name":"A","Type":1,"Result":"1"},
{"Name":"B","Type":3,"Result":"1"},
{"Name":"B","Type":2,"Result":"1"},
{"Name":"B","Type":1,"Result":"0"},
]
Can someone tell me what's the issue with my code?
I want to create table for dynamic JSON data which may not have cell values for all the columns. With this code, I don't see entry in column 5 for A as 1.
function get_prop(obj, prop) {
return prop.split('.').reduce((o,k) => obj[k], obj);
}
function coll2tbl(json, row_header, col_header, cell) {
var table = {};
var row_headers = [];
var cols = {};
json.map(function(a) {
var h = get_prop(a, row_header);
if (h in table === false) {
table[h] = {};
row_headers.push(h);
}
var c = get_prop(a, col_header);
cols[c] = null;
table[h][c] = get_prop(a, cell);
});
var cells = [];
for (var row in table) {
cells.push(Object.values(table[row]));
}
console.log('row_headers' + row_headers);
console.log('Object.keys(cols)' + Object.keys(cols));
console.log('cells' + cells);
var headerRow = '<th>' + capitalizeFirstLetter('TestName') + '</th>';
var colKeys = Object.keys(cols);
colKeys.map(function(col) {
headerRow += '<th>' + capitalizeFirstLetter(col) + '</th>';
});
var bodyRows = '';
for (var i in cells) {
bodyRows += '<tr>';
bodyRows += '<td>' + row_headers[i] + '</td>';
for (var j in cells[i]) {
console.log('Processing row: ' + row_headers[i] + ' result: ' + cells[i][j] + ' i=' + i + ' j=' + j);
bodyRows += '<td>';
if (cells[i][j] === "1") {
bodyRows += '<font color="green">' + cells[i][j] + '</font>';
}
else if (cells[i][j] === "0") {
bodyRows += '<font color="red">' + cells[i][j] + '</font>';
}
else if (cells[i][j] === "-1") {
bodyRows += '<font color="orange">' + cells[i][j] + '</font>';
}
else {
bodyRows += "-";
}
bodyRows += '</td>';
}
bodyRows += '</tr>';
}
//return { row_headers, col_headers: Object.keys(cols), cells };
return ('<table> <thead><tr>' + headerRow + '</tr></thead><tbody>' + bodyRows + '</tbody></table>');
}
function capitalizeFirstLetter(string) {return
string.charAt(0).toUpperCase() + string.slice(1);
}
coll2tbl(items, 'Name', 'Type', 'Result');
My table should like like this:
Name 1 2 3 4 5
A 1 1 - - 1
B 1 1 1 - -
The answer https://stackoverflow.com/a/52199138/10320683 is of course correct, but if you need or want to stick to your specific code, you can put this below your json.map (which should by the way use forEach and not map, since you do not use the returned array anyways)
for (var col in cols) {
for (row in table) {
if (!table[row].hasOwnProperty(col)) {
table[row][col] = "-";
}
}
}
The reason why your code did not work is that by iterating over the rows, you do not get all the possible type properties, which becomes clear if you inspect your table variable: { a: {1: "1", 2: "0", 5: "1"}, b: {...}} (this is missing the 3 type property), so by calling Object.values(table[row]) later on, you get the following array for your cells: ["1", "0", "1"], but you do have 4 columns, so the "Type 5" result (1) gets shifted one column to the left.
Also, you need to be careful because your code is relying on the sorting that Object.values() produces, which means that if you want to change the order of your columns, your code would not work.

Is there way to modify Number class

At clasic windows calculator, nubers are separated by comma, like: 4,5
I wish to have it same in flash, but:
Number("4,5") //output: NaN
Is there any way modify Number class to get this result?
Number("4,5") //output: 4.5
Number("4.5") //output: 4.5
Also string with spaces can be considered as number...
trace(Number("10000" )) //output: 10000
trace(Number("10 000")) //output: NaN
one more example about numbers which can be fixed:
trace(4.3 - 1.1) //output 3.1999999999999997
trace(Number(4.3 - 1.1).toFixed(1)) //output: 3.2
Instead of using Number , use a function and send the values to it , just like this
function convertNumber(var:String):Number
{
var arr:Array;
arr = var.split(",");
if(arr.length >0)
{
var sendStr:String = arr[0] + "." + arr[1];
return Number(sendStr);
}
arr = var.split(" ");
if(arr.length >0)
{
var sendStr:String = arr[0] + arr[1];
return Number(sendStr);
}
return Number(var)
}
use convertNumber(4,5) to get output as 4.5

Need help with setTextFormat (AS3)

I'm trying to make an rss reader with Flash CS5.5. It's almost finished but i couldn't style news titles. The problem is some parts of a textfield needs to be bold and colored. Here's my code:
var num:int = 0;
var tempText:String;
var titleStr:String;
var timeStr:String;
var descriptionStr: String;
function rssLoaded(evt:Event):void {
rssXML = XML(rssLoader.data);
// trace(rssXML);
num = 0;
for (var rssTitle:String in rssXML.channel.item) {
// Set title
tempText = rssXML.channel.item[rssTitle].title;
tempText = tempText.slice(6);
titleStr = tempText + "\r\n";
// Set description
tempText = rssXML.channel.item[num].description;
// Detect if beginning with tags
if ((tempText.charCodeAt(0) == 60) && (tempText.charCodeAt(1) == 73)) {
tempText = tempText.slice(tempText.search("/>") + 2, tempText.search("<img"));
} else {
tempText = tempText.slice(0, 140);
}
// Detect if still contains tags
if ((tempText.indexOf("<") != -1) || (tempText.indexOf(">") != -1)) {
num++;
continue;
}
// Detect if beginning with space
for (var num2:int=0; tempText.charCodeAt(0) == 32 || tempText.charCodeAt(0) == 160; num2++) {
tempText = tempText.slice(1);
}
descriptionStr = tempText + "...\r\n\r\n";
main_txt.appendText(titleStr);
main_txt.setTextFormat(title_tf, main_txt.text.length - titleStr.length, titleStr.length-2);
main_txt.appendText(descriptionStr);
num++;
}
}
var title_tf:TextFormat=new TextFormat();
title_tf.bold=true;
When I test the code, I'm seeing that only the first line is bold, while all titles needs to be bold. Sorry for my English.
Sincerely
It would be much simpler to style the text using the TextField.htmlText property:
title_tf.htmlText = "<b>" + titleTextString + "</b><br/>" + bodyTextString;
This approach would also allow you to use CSS like this:
title_tf.styleSheet = myImportedStyleSheet;
title_tf.htmlText = "<span class='titleClass'>" + titleTextString + "</span><br/><span class='bodyClass'>" + bodyTextString + "</span>";

ActionScript - Formatting Zero With NumberFormatter?

i've assigned properties to a NumberFormatter object so that formatted values contain a leading zero, trailing zeros and a 2 decimal places.
the formatting works unless the number being formatted is 0. how can i format a 0 with the set properties so that 0 becomes 0.00?
var numFormat:NumberFormatter = new NumberFormatter(LocaleID.DEFAULT);
numFormat.leadingZero = true;
numFormat.trailingZeros = true;
numFormat.fractionalDigits = 2;
trace(numFormat.formatNumber(46)); //46.00
trace(numFormat.formatNumber(0.556849)); //0.56
trace(numFormat.formatNumber(0)); //0
[EDIT]
i've remedied this problem by manually appending the locale decimal separator with the desired number of fractionalDigits if the formatted number is 0:
if (myFormattedNumber.text == "0" && numFormat.fractionalDigits)
{
myFormattedNumber.appendText(numFormat.decimalSeparator);
for (var i:uint = 0; i < numFormat.fractionalDigits; i++)
myFormattedNumber.appendText("0");
}
i'm still very interested in knowing if this is a bug or a feature, but it seems like a oversight to me.
It's not sexy, but this was similar to what I used when I ran into a similar issue:
function numberFormat(number:*, maxDecimals:int = 2, forceDecimals:Boolean = false, siStyle:Boolean = true):String
{
var i:int = 0, inc:Number = Math.pow(10, maxDecimals), str:String = String(Math.round(inc * Number(number))/inc);
var hasSep:Boolean = str.indexOf(".") == -1, sep:int = hasSep ? str.length : str.indexOf(".");
var ret:String = (hasSep && !forceDecimals ? "" : (siStyle ? "," : ".")) + str.substr(sep+1);
if (forceDecimals) for (var j:int = 0; j <= maxDecimals - (str.length - (hasSep ? sep-1 : sep)); j++) ret += "0";
while (i + 3 < (str.substr(0, 1) == "-" ? sep-1 : sep)) ret = (siStyle ? "." : ",") + str.substr(sep - (i += 3), 3) + ret;
return str.substr(0, sep - i) + ret;
}
trace("zero: " + numberFormat(0, 2, true, false))
Full article here
How about Number(value).toFixed(2) ?