How to loop 2 Dimensional Array on Google Script - sorting

There is a problem with my run time execution in my code. It takes too long to finish, since I have to loop a large amounts of data to look for matching data. I used array on the first loop value though, I don't know how to array the second value without affecting the first array.
Name of the first array : Source
Name of the Second array : Target
Here is my Code:
function inactive_sort_cebu() {
var ss = SpreadsheetApp.openById('169vIeTMLK4zN5VGCw1ktRteCwMToU8eGABFDxg52QBk');
// var sheet = ss.getSheets()[0];// Manila Roster
var sheet2 = ss.getSheets()[1];// Cebu Roster
var column = sheet2.getRange("C1:C").getValues();
var last = column.filter(String).length;
// -----------------------------------------------------------
var ss1 = SpreadsheetApp.openById('153ul2x2GpSopfMkCZiXCjmqdPTYhx4QiOdP5SBYzQkc');
// var sched_sheet = ss1.getSheets()[0];// ScheduledForm_Manila
var sched_sheet2 = ss1.getSheets()[1];// ScheduledForm_Cebu
var column2 = sched_sheet2.getRange("C1:C").getValues();
var last2 = column2.filter(String).length;
//// -------------------------Manila-Roster---------------------------------
var i= 2;
var column3 = sched_sheet2.getRange("J1:J").getValues();
var a = column3.filter(String).length - 1;
// var a = 0;
try{
var source = sched_sheet2.getRange("C2:C").getValues();
for (a;a<=last2;){
/// this is the code that i need to array without affecting the other array which is the source variable
var target = sheet2.getRange("C"+ i).getValue();
if(source[a] == target){
// Get "No Schedule Request data on Cell H
var data = sched_sheet2.getRange("H"+(a+2)).getValue();
// Get "Schedule Request data on Cell F
var data1 = sched_sheet2.getRange("F"+(a+2)).getValue();
var condition_1 = sched_sheet2.getRange("D"+(a+2)).getValue();
var condition_2 = sched_sheet2.getRange("G"+(a+2)).getValue();
var format_Con_2 = Utilities.formatDate(condition_2, 'Asia/Manila', 'm/dd/yyyy');
var condition_3 = sched_sheet2.getRange("K"+ (a+2)).getValue();
var date = new Date();
var date_Manila = Utilities.formatDate(date, 'Asia/Manila', 'm/dd/yyyy');
if(condition_1 == "No Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("N - "+ data);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else if (condition_1 == "Schedule Request" && format_Con_2 <= date_Manila && condition_3 ==""){
sheet2.getRange("AA"+ i).setValue("Y - "+data1);
sched_sheet2.getRange("J"+ (a+2)).setValue("Cebu");
sched_sheet2.getRange("K"+ (a+2)).setValue("Done");
a++;
}
else{a++;}
i=2;}
else {i++;}
}

This is a simple example of a web app that puts an editable spreadsheet on an HTML Page. Publish as a webapp. I loops through the 2D array that you get when you getValues from the getDataRange() method. In this case I'm just intertwining html into the mix.
Code.gs:
var SSID='SpreadsheetID';
var sheetName='Sheet Name';
function htmlSpreadsheet(mode)
{
var mode=(typeof(mode)!='undefined')?mode:'dialog';
var br='<br />';
var s='';
var hdrRows=1;
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
s+='<table>';
for(var i=0;i<rngA.length;i++)
{
s+='<tr>';
for(var j=0;j<rngA[i].length;j++)
{
if(i<hdrRows)
{
s+='<th id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
else
{
s+='<td id="cell' + i + j + '">' + '<input id="txt' + i + j + '" type="text" value="' + rngA[i][j] + '" size="10" onChange="updateSS(' + i + ',' + j + ');" />' + '</th>';
}
}
s+='</tr>';
}
s+='</table>';
//s+='<div id="success"></div>';
s+='</body></html>';
switch (mode)
{
case 'dialog':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
userInterface.append(s);
SpreadsheetApp.getUi().showModelessDialog(userInterface, 'Spreadsheet Data for ' + ss.getName() + ' Sheet: ' + sht.getName());
break;
case 'web':
var userInterface=HtmlService.createHtmlOutputFromFile('htmlss').setWidth(1000).setHeight(450);
return userInterface.append(s).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
}
function updateSpreadsheet(i,j,value)
{
var ss=SpreadsheetApp.openById(SSID);
var sht=ss.getSheetByName(sheetName);
var rng=sht.getDataRange();
var rngA=rng.getValues();
rngA[i][j]=value;
rng.setValues(rngA);
var data = {'message':'Cell[' + Number(i + 1) + '][' + Number(j + 1) + '] Has been updated', 'ridx': i, 'cidx': j};
return data;
}
function doGet()
{
var output=htmlSpreadsheet('web');
return output;
}
htmlss.html:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function() {
});
function updateSS(i,j)
{
var str='#txt' + String(i) + String(j);
var value=$(str).val();
$(str).css('background-color','#ffff00');
google.script.run
.withSuccessHandler(successHandler)
.updateSpreadsheet(i,j,value)
}
function successHandler(data)
{
$('#success').text(data.message);
$('#txt' + data.ridx + data.cidx).css('background-color','#ffffff');
}
console.log('My Code');
</script>
<style>
th{text-align:left}
</style>
</head>
<body>
<div id="success"></div>

Related

Disable button on ajax submit

I have the following JS and HTML code and I want to disable the button when ajax request is submitting so the user wont be able to double click and disturb the process.
function doReshare(_intPostId) {
if(typeof cLogin === 'undefined')
var cLogin = checkLogin();
if(cLogin!=true)
return;
var date = new Date();
var mainId = _intPostId;
var type = 1;
var active = 0;
var postFinded = 0;
jQuery(".reshare_" + _intPostId).each(function() {
postFinded = 1;
objElement = jQuery(this);
if(objElement.hasClass('sm2_playing') || objElement.hasClass('sm2_paused')) {
// track is active
active = 1;
}
if(objElement.hasClass('is_album')) {
mainId = objElement.closest('div.playlist-box').attr('id').replace('album_', '');
// mainId = objElement.data('mainid');
}
var intLikesCurrentCount = parseInt(objElement.find(".likes_count").first().text(), 10);
if(!objElement.find(".refeed_fct").hasClass("active")) {
if(active)
jQuery('.player-icons.dorepost').addClass('active');
objElement.find(".refeed_fct").addClass("active");
//objElement.find(".likes_count").html("<i class=\"fa fa-heart-o\"></i> " + (intLikesCurrentCount + 1));
} else {
objElement.find(".refeed_fct").removeClass("active");
if(active)
jQuery('.player-icons.dorepost').removeClass('active');
type = 0;
//objElement.find(".likes_count").html("<i class=\"fa fa-heart-o\"></i> " + (intLikesCurrentCount - 1));
}
});
if(!postFinded) {
if(!jQuery(".player-icons.dorepost").hasClass("active")) {
jQuery('.player-icons.dorepost').addClass('active');
} else {
jQuery('.player-icons.dorepost').removeClass('active');
}
}
jQuery("#vowave").append('<img width="1" height="1" src="/reshare/' + mainId + '/' + type + '?time=' + date.getTime() + '" />');
}
and the html
<span class="refeed_fct" onclick="doReshare(10309)">
<i class="fa fa-retweet"></i> <div class="inline hidden-mobile">Repost</div>
</span>
Thank you
Maybe you should set the objElement's onclick listener to an empty function

How to set kendo datepicker (popup date view) to specific year (1435) without set value(want value to be null)

i make custom mvc control with two kendo datepicker to display (gregi and hijri) date in partial view and if i change date of any one it's change the other to equivalent date
cause to kendo limitation to deal with Hijri calender i make some modification to display correct date i use culture and set max date to hijri to 29/12/1600
every thing is ok if i set value(DateTime.Now) to hijri calender
but i want it display null and user select value but if i remove value and when user open calender the year show is 1600 i want to display 1435 and keep value null
her is my code
Controller
public class UserControl_GHDate
{
public DateTime? GregiDate { get; set; }
[Column(TypeName = "DateTime2")]
public DateTime? HijriDate
{
get
{
if (GregiDate==null)
{
return null;//DateTime.Now;
}
else
{
return GregiDate;
}
}
set { }
}
}
Razor
#model MVC_ERP.Models.UserControl_GHDate
<script src="#Url.Content("~/Scripts/jquery.globalize/globalize.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.ar-SA.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.globalize/cultures/globalize.culture.en-US.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/kendo/cultures/kendo.culture.ar-SA.min.js")"></script>
#Html.Kendo().DatePickerFor(model => model.GregiDate).Format("dd/MM/yyyy").Culture("en-US").HtmlAttributes(new { #class = "kendo", style = "width:49%; max-width:280px" }).Events(e => e.Change("GregiChange"))
#Html.Kendo().DatePickerFor(model => model.HijriDate).Value(DateTime.Now).Footer(false).Max("12/29/1600").Culture("ar-SA").Min(new DateTime(1300, 1, 1)).Format("dd/MM/yyyy").HtmlAttributes(new { #class = "kendo", style = "width:49%; max-width:280px" }).Events(e => e.Change("HijriChange"))
<script>
kendo.cultures["ar-SA"].calendars.standard.firstDay =5;
//kendo.cultures["ar-SA"].calendars.standard.months.namesAbbr[0] = "bbb"; //change name of month
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[0] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[1] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[2] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[3] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[4] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[5] = "";
kendo.cultures["ar-SA"].calendars.standard.days.namesShort[6] = "";
function GregiChange(e) {
//alert(this.Name())
var GregId = this.element.prop("id");
var arr = GregId.split('_');
var HijId = arr[0] + '_HijriDate';
if ($('#' + GregId).data('kendoDatePicker').value() == null)
{
$('#' + HijId).data('kendoDatePicker').value(null)
return
}
var d = new Date($('#' + GregId).data('kendoDatePicker').value())
//d.setMonth(d.getMonth() + 1);
var j = d.toLocaleDateString("en-US")
//var z = Globalize.cultures["ar-SA"].calendars.standard.convert.toGregorian("1434", "02", "11");
var z = Globalize.cultures["ar-SA"].calendars.standard.convert.fromGregorian(d);
var y = z.toString()
var arrD = y.split(',');
var year = arrD[0]
var month =(arrD[1]==0?1:(eval(arrD[1])+1))
var day = arrD[2]
var dat = day + '/' + month + '/' + year
$('#' + HijId).data('kendoDatePicker').value(dat)
}
function HijriChange() {
var HijId = this.element.prop("id");
var arr = HijId.split('_');
var GregId = arr[0] + '_GregiDate';
if ($('#' + HijId).data('kendoDatePicker').value() == null) {
$('#' + GregId).data('kendoDatePicker').value(null)
return
}
var d = new Date($('#' + HijId).data('kendoDatePicker').value())
var HD = d.getDate() + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
HDMY= d.getDate() + '/' + (d.getMonth()+1)
if (d.getDate() == 31 || HDMY == '30/12' || HDMY == '30/10' || HDMY == '30/8' || HDMY == '30/6' || HDMY == '30/4' || HDMY == '30/2')
{
alert(HD + ' not valid hijri date')
return;
}
var z = Globalize.cultures["ar-SA"].calendars.standard.convert.toGregorian(d.getFullYear(), (d.getMonth() + 1), d.getDate());
var u = new Date(z)
var year = u.getFullYear();
var month = (u.getMonth() == 0 ? 12 : u.getMonth());
var day = u.getDate()+1;
var dat = day+ '/' + month+ '/' + year;
$('#' + GregId).data('kendoDatePicker').value(dat)
}
$(".k-datepicker input").val('');
</script>
Thanks
I think kendo date picker has a min value option try specify the min value with a year of 1435

Does not want to be inserted as html in CKeditor

onOk: function() {
var dialog = this;
var contentFromTextarea = dialog.getValueOf('tab-main','content');
var rowArray = new Array();
var cellArray = new Array();
var row = '';
rowArray = contentFromTextarea.split(';');
for (var i = 0; i < rowArray.length-1; i++)
{
cellArray[i] = rowArray[i].split(':');
row += '<div>' + '<span>' + cellArray[i][0] + '</span>' + '<span>' + cellArray[i][1] + '</span>' + '</div>'
}
row = '<div>' + row + '</div>';
editor.insertHtml(row);
}
Does not want to be inserted as html in CKeditor. Why?
Thanks for help.
Try displaying "row" just before you run the editor.insertHtml(row);
command just to make sure you html tags are well formed. why are you adding a div tag inside another div tag?

Scroll Events in TouchGridPanel

I am building a mobile application using Sencha Touch 1.0. I need to display report, for that am using grid given by Ext.ux.TouchGridPanel.
It is working fine.
Where as I need to capture Scroll event in Ext.ux.TouchGridPanel.
I have added 'scroll' in bubble event of Dataview.
I am also trying to capture the event after the Dataview created.
But nothing seems to be working. Below is the code which I have changed.
Does anybody has any idea how to capture the start of scroll event?
Thanks in advance.
Ext.ux.TouchGridPanel = Ext.extend(Ext.Panel, {
layout: "fit",
multiSelect: false,
initComponent: function () {
var me = this;
me.items = me.dataview = me.buildDataView();
Ext.ux.TouchGridPanel.superclass.initComponent.call(me);
var store = me.store;
store.on("update", me.dispatchDataChanged, me);
var dataview = me.dataview;
dataview.on('scroll', me.startScroll);
},
dispatchDataChanged: function (store, rec, operation) {
var me = this;
me.fireEvent("storeupdate", store, rec, operation);
},
startScroll: function (scroller, offset) {
console.log('is this event captured???')
var me = this;
me.fireEvent("scroll", this.scroller, offset);
},
buildDataView: function () {
var me = this, colModel = me.colModel, colNum = me.getColNum(false), cellWidth = 100 / colNum,
colTpl = '<div class="x-grid-head">';
colTpl += '<thead><tr class="x-grid-header">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + (col.width - 4) + "%") : '';
colTpl += '<th class="x-grid-cell" ' + width + ' style="' + col.style + '" >' + col.header + '</th>';
}
colTpl += '</tr></thead>';
colTpl += '<tbody ><tpl for="."><tr class="x-grid-row">';
for (var i = 0; i < colModel.length; i++) {
var col = colModel[i];
var width = (Ext.isDefined(col.width)) ? ("width =" + col.width + "%") : '';
colTpl += '<td class="x-grid-cell" style="' + col.style + '" >{' + col.mapping + '}</td>';
}
colTpl += '</tr></tpl></tbody>';
colTpl += '</table></div>'
return new Ext.DataView({
store: me.store,
itemSelector: "tr.x-grid-row",
simpleSelect: me.multiSelect,
scroll: me.scroll,
tpl: new Ext.XTemplate(colTpl,
{
isRowDirty: function (dirty, data) {
return dirty ? "x-grid-row-dirty" : "";
}
}
),
prepareData: function (data, index, record) {
var column,
i = 0,
ln = colModel.length;
var prepare_data = {};
prepare_data.dirtyFields = {};
for (; i < ln; i++) {
column = colModel[i];
if (typeof column.renderer === "function") {
prepare_data[column.mapping] = column.renderer.apply(me, [data[column.mapping], column, record, index]);
} else {
prepare_data[column.mapping] = data[column.mapping];
}
}
prepare_data.isDirty = record.dirty;
prepare_data.rowIndex = index;
return prepare_data;
},
bubbleEvents: [
"beforeselect",
"containertap",
"itemdoubletap",
"itemswipe",
"itemtap",
"selectionchange",
"scroll"
]
});
},
// #private
onScrollStart: function () {
console.log("Are you coming here");
var offset = this.scroller.getOffset();
this.closest = this.getClosestGroups(offset);
this.setActiveGroup(this.closest.current);
},
// #private
onScroll: function (scroller, pos, options) {
}
});
Ext.reg("touchgridpanel", Ext.ux.TouchGridPanel);
We can directly access dataview scroller and check event of the same.
For eg.
newGrid = new Ext.ux.TouchGridPanel({....
after creation of the Panel just access its dataview scroller
newGrid.dataview.scroller.on('scroll', scrollGrid1);
var scrollGrid1 = function(scroller, offsets){
console.log(' Grid scrolling with offset ' + offsets.x + ' & ' + offsets.y);
}

Twitter and jQuery , render tweeted links

I am using jquery ajax to pull from the twitter api, i'm sure there's a easy way, but I can't find it on how to get the "tweet" to render any links that were tweeted to appear as a link. Right now it's only text.
$.ajax({
type : 'GET',
dataType : 'jsonp',
url : 'http://search.twitter.com/search.json?q=nettuts&rpp=2',
success : function(tweets) {
var twitter = $.map(tweets.results, function(obj, index) {
return {
username : obj.from_user,
tweet : obj.text,
imgSource : obj.profile_image_url,
geo : obj.geo
};
});
UPDATE:
The following function (plugin) works perfectly.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 100,
fadeSpeed : 500,
tweetName: 'jquery'
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q="+settings.tweetName+"&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
Within my Ready Statement :
$.socialFader({ tweetHolder:"#twitter", tweetName:"nettuts", tweetCount:2 });
Here is a plugin I wrote which really simplifies the tweet/json aggregation then parsing. It fades the tweets in and out. Just grab the needed code. Enjoy.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=jquery&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
You need to parse the tweet content, find the urls and then put them in between yourself.
Unfortunately, at the moment, the search API doesn't have the facility to break out tweet entities (i.e., links, mentions, hashtags) like some of the REST API methods. So, you could either parse out the entities yourself (I use regular expressions) or call back into the rest API to get the entities.
If you decide to call back into the REST API, and once you have extracted the status ID from the search API results, you would make a call to statuses/show like the following:
http://api.twitter.com/1/statuses/show/60183527282577408.json?include_entities=true
In the resultant JSON, notice the entities object.
"entities":{"urls":[{"expanded_url":null,"indices":[68,88],"url":"http:\/\/bit.ly\/gWZmaJ"}],"user_mentions":[],"hashtags":[{"text":"wordpress","indices":[89,99]}]}
You can use the above to locate the specific entities in the tweet (which occur between the string positions denoted by the indices property) and transform them appropriately.
If you prefer to parse the entities yourself, here are the (.NET Framework) regular expressions I use:
Link Match Pattern
(?:<\w+.*?>|[^=!:'"/]|^)((?:https?://|www\.)[-\w]+(?:\.[-\w]+)*(?::\d+)?(?:/(?:(?:[~\w\+%-]|(?:[,.;#:][^\s$]))+)?)*(?:\?[\w\+%&=.;:-]+)?(?:\#[\w\-\.]*)?)(?:\p{P}|\s|<|$)
Mention Match Pattern
\B#([\w\d_]+)
Hashtag Match Pattern
(?:(?:^#|[\s\(\[]#(?!\d\s))(\w+(?:[_\-\.\+\/]\w+)*)+)
Twitter also provides an open source library that helps capture Twitter-specific entities like links, mentions and hashtags. This java file contains the code defining the regular expressions that Twitter uses, and this yml file contains test strings and expected outcomes of many unit tests that exercise the regular expressions in the Twitter library.
How you process the tweet is up to you, however I process a copy of the original tweet, and pull all the links first, replacing them in the copy with spaces (so as not to modify the string length.) I capture the start and end locations of the match in the string, along with the matched content. I then pull mentions, then hashtags -- again replacing them in the tweet copy with spaces.
This approach ensures that I don't find false positives for mentions and hashtags in any links in the tweet.
I slightly modified previous one. Nothing lefts after all tweets disappears one by one.
Now it checks if there is any visible tweets and then refreshes tweets.
(function($) {
$.socialFader = function(options) {
var settings = {
tweetHolder : null,
tweetCount : 99,
fadeSpeed : 500,
};
if (options) {
$.extend(settings, options);
};
var URL = "http://search.twitter.com/search.json?q=istanbul&rpp=" + settings.tweetCount + "&callback=?";
function relative_time(time_value) {
var values = time_value.split(" ");
time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
var parsed_date = Date.parse(time_value);
var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
delta = delta + (relative_to.getTimezoneOffset() * 60);
var r = '';
if (delta < 60) {
r = 'a minute ago';
} else if(delta < 120) {
r = 'couple of minutes ago';
} else if(delta < (45*60)) {
r = (parseInt(delta / 60)).toString() + ' minutes ago';
} else if(delta < (90*60)) {
r = 'an hour ago';
} else if(delta < (24*60*60)) {
r = '' + (parseInt(delta / 3600)).toString() + ' hours ago';
} else if(delta < (48*60*60)) {
r = '1 day ago';
} else {
r = (parseInt(delta / 86400)).toString() + ' days ago';
}
return r;
};
String.prototype.hashify = function() {
return this.replace(/#([A-Za-z0-9\/\.]*)/g, function(m) {
return '<a target="_new" href="http://twitter.com/search?q=' + m.replace('#','') + '">' + m + "</a>";
});
};
String.prototype.linkify = function(){
return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function(m) {
return m.link(m);
});
};
String.prototype.atify = function() {
return this.replace(/#[\w]+/g, function(m) {
return '' + m + "";
});
};
$.getJSON(URL, function(JSON) {
$(settings.tweetHolder).find('li.cycles').remove();
$.each(JSON.results, function(i, tweet) {
var profilePicture = tweet.profile_image_url;
var userLink = tweet.from_user;
var text = tweet.text;
text = text.linkify().atify().hashify();
var createdAt = new Date(tweet.created_at);
var myTweet = '' + userLink + ' ';
myTweet += text;
$(settings.tweetHolder).append('<li class="cycles">' + myTweet + '</li>');
});
var elements = $(settings.tweetHolder).children();
var timeOutStart = 5000;
function fader(elementId) {
setTimeout(function() {
$(elements[elementId]).fadeOut(settings.fadeSpeed, function() {
$(elements[elementId + 1]).fadeIn(settings.fadeSpeed);
});
if (jQuery('#twitter ul li.cycles:visible').length==1) {
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
}
}, timeOutStart * (elementId));
};
for (var j = 0; j < elements.length; j++) {
fader(j);
};
});
};
})(jQuery);
jQuery(document).ready(function(){
jQuery.socialFader({ tweetHolder:"#twitter ul", tweetCount:5 });
});

Resources