Extracting links and twitter replies from a string - actionscript-3

I am getting a string from Twitter into my Actionscript which is a unformatted string. I want to be able to extract any links and or any #replies from the string, then display it in htmlText.
So far I have this
var txt:String = "This is just some text http://www.thisisawebsite.com and some more text via #sumTwitter";
var twitterText:String = txt.slice(txt.indexOf("#"),txt.indexOf(" ",txt.indexOf("#")));
var urlText:String = txt.slice(txt.indexOf("http"),txt.indexOf(" ",txt.indexOf("http")));
var newURL:String = ""+urlText+"";
var arr:Array = txt.split(urlText);
var newString:String = arr[0] + newURL + arr[1];
var txtField:TextField = new TextField();
txtField.width = 500;
txtField.htmlText = newString;
addChild(txtField);
This is fine for extracting links, which finish with a space. But what if, like the #sumTwitter, it finishes at the end of the string. And also what if there are multiple links or #'s, is the best way to put it in a while loop?

Regular expressions are the best option for what you want, I think.
Check Grant Skinner's RegExr. You could write and test your own RegExp there, which is very convenient. But you also can find a lot of useful ready-to-use regexps created by different users. Check out the "community" tab in the right panel. There, search by some meaningful keywords like "twitter" and "url" and you'll get a good number of options.
For example,
Grab urls:
http://regexr.com?2s5m4
Capture twitter usernames:
http://regexr.com?2s5m7

Related

Making a simple flexible translate function in nodejs

In nodejs I have these (very long) translation files
gb.json (english)
{
"transHi":"Hello",
"transBye":"Goodbye"
}
de.json (german)
{
"transHi":"Gutentag",
"transBye":"Auf Wiedersehen"
}
I have a lot of controllers that all need these texts available in the many languages so I can call them when ever needed.
The obvious way would be something like this in my app.js:
global.gb = require('../global/language/gb.json');
global.de = require('../global/language/de.json');
And when I need a text I would call like:
myText = global.gb.transHi
myText = global.de.transHi
But!! the language is always determined by a variable
usersLanguage = "de"
myText = global.usersLanguage.transHi
And that wont work.
I also tried:
usersLanguage = "de"
myText = global.usersLanguage.transHi
Perhaps I could solve it with a function that has a long switch structure
var findText = (language,textkey) => {
switch(language) {
case "gb:
return gb.textkey
break;
case "de:
return de.textkey
break;
}
}
myText = translate(usersLanguage, "transHi");
But I cant seem to make that work either.
How would I do this in a simple and flexible way?
UPDATE: Is it possible to do this?
Any object property accessed via . can also be accessed using array index notation []. So,
var langObj = texts.gb;
is the same as
var langObj = texts["gb"];
which is also the same as
var lang = "gb";
var langObj = texts[lang];
Same for the textkey, using the .textkey you get the property called textkey, which probably doesn't exist. If you want a different property depending on the value of the variable textkey, do
var text = langObj[textkey];

trying to get properties of objects inside object properties

Sometimes JavaScript is playing with me (although the deal was that I would be playing with it...) This test code below keeps resisting so I'm looking for a little help from more clever people around here.
Answering to a recent question I tried to create a readable list of all the color IDs useable in Google Advanced Calendar API.
The request is very simple : Calendar.Colors.get()
The response is an object with a couple of properties, each one being other objects with other properties.
I can go down to the second level but the last -and most useful in this case - level returns a disturbing "undefined" (see partial log below)
And that's my question...
code with comments :
function getColorList(){
var colors = Calendar.Colors.get();
//Logger.log(JSON.stringify(colors));
for(var cat in colors){
Logger.log("category "+cat+" = "+JSON.stringify(colors[cat])+'\n\n')
}
// from there I try the "event" category
var events = colors["event"];
Logger.log('object colors["event"] = '+ JSON.stringify(events))
// then I try to get every properties in this object
for(var val in events){
Logger.log("key "+val+" = "+JSON.stringify(events[val]))
}
}
Full log is viewable here (externalized to keep this reasonably short)
Looks like (key) may be indicating a read-only definition as Sandy was eluding to.
Just make your own object from colors to loop through after converting it to string:
var json = JSON.stringify(colors["event"]);
var myObj = JSON.parse(json);
for(var val in myObj){
Logger.log("key "+ val +" = "+JSON.stringify(myObj[val]))
}

Can Microsoft Translator answer "does a word exist" queries?

I want to know if the API can do something like this:
I send a word in an predetermined language
API answer if the word exist in that language.
To add some context to the question, the idea is to develop a Scrabble like game, and I'm investigating a method to detect valid words, for all (or most common) languages that is.
I've already asked for a solution in one of their forums, but they are kind of dead.
I tested the MS translator service.
var result = MST.TranslateText("xyz", "en", "de"); // custom routine that calls MS service
var result2 = MST.TranslateText("dog", "en", "de");
var result2 = MST.TranslateText("sdfasfgd", "en", "de");
Result = XYZ // source xyz
Result2 = Hund // source dog
Result3 = sdfasfgd // sdfasfgd
Looks like when not found or a translation is not possible the string
is returned untouched.
The only strange behavior i've noted is conversion to uppercase for Some 3 letter scenarios that
arent obvious TLAs in either langauge.
public string TranslateText(string sourceText, string fromLang, string toLang) {
var httpRequestProperty = GetAuthorizationRequestHeader();
var msTransClient = new TranslatorService.LanguageServiceClient();
// Creates a block within which an OperationContext object is in scope.
using (var scope = new OperationContextScope(msTransClient.InnerChannel))
{
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpRequestProperty;
//Keep appId parameter blank as we are sending access token in authorization header.
var translationResult = msTransClient.Translate("", sourceText, fromLang, toLang, "text/plain", "");
return translationResult;
}
}

How do I find the page number/number of pages in a document?

I want to create a new document based on a template and need to know when my insertion or append results in a new page in the final printed output is there any property/attribute eg number of pages that can be used for this?
I've search this a lot in the past and I don't think there's any property or any other way to know page info.
The solution I use is to insert page breaks on my template or via the script, using my own knowledge of how my template works, i.e. how much space it takes as I iterate, etc.
And then I know which page I am by counting the page breaks.
Anyway, you could an enhancement request on the issue tracker.
One way to get total number of pages:
function countPages() {
var blob = DocumentApp.getActiveDocument().getAs("application/pdf");
var data = blob.getDataAsString();
var re = /Pages\/Count (\d+)/g;
var match;
var pages = 0;
while(match = re.exec(data)) {
Logger.log("MATCH = " + match[1]);
var value = parseInt(match[1]);
if (value > pages) {
pages = value;
}
}
Logger.log("pages = " + pages);
return pages;
}

JSFL: convert text from a textfield to a HTML-format string

I've got a deceptively simple question: how can I get the text from a text field AND include the formatting? Going through the usual docs I found out it is possible to get the text only. It is also possible to get the text formatting, but this only works if the entire text field uses only one kind of formatting. I need the precise formatting so that I convert it to a string with html-tags.
Personally I need this so I can pass it to a custom-made text field component that uses HTML for formatting. But it could also be used to simply export the contents of any text field to any other format. This could be of interest to others out there, too.
Looking for a solution elsewhere I found this:
http://labs.thesedays.com/blog/2010/03/18/jsfl-rich-text/
Which seems to do the reverse of what I need, convert HTML to Flash Text. My own attempts to reverse this have not been successful thus far. Maybe someone else sees an easy way to reverse this that I’m missing? There might also be other solutions. One might be to get the EXACT data of the text field, which should include formatting tags of some kind(XML, when looking into the contents of the stored FLA file). Then remove/convert those tags. But I have no idea how to do this, if at all possible. Another option is to cycle through every character using start- and endIndex, and storing each formatting kind in an array. Then I could apply the formatting to each character. But this will result in excess tags. Especially for hyperlinks! So can anybody help me with this?
A bit late to the party but the following function takes a JSFL static text element as input and returns a HTML string (using the Flash-friendly <font> tag) based on the styles found it its TextRuns array. It's doing a bit of basic regex to clear up some tags and double spaces etc. and convert /r and /n to <br/> tags. It's probably not perfect but hopefully you can see what's going on easy enough to change or fix it.
function tfToHTML(p_tf)
{
var textRuns = p_tf.textRuns;
var html = "";
for ( var i=0; i<textRuns.length; i++ )
{
var textRun = textRuns[i];
var chars = textRun.characters;
chars = chars.replace(/\n/g,"<br/>");
chars = chars.replace(/\r/g,"<br/>");
chars = chars.replace(/ /g," ");
chars = chars.replace(/. <br\/>/g,".<br/>");
var attrs = textRun.textAttrs;
var font = attrs.face;
var size = attrs.size;
var bold = attrs.bold;
var italic = attrs.italic;
var colour = attrs.fillColor;
if ( bold )
{
chars = "<b>"+chars+"</b>";
}
if ( italic )
{
chars = "<i>"+chars+"</i>";
}
chars = "<font size=\""+size+"\" face=\""+font+"\" color=\""+colour+"\">"+chars+"</font>";
html += chars;
}
return html;
}