Created
April 30, 2013 20:40
-
-
Save oshikryu/5491777 to your computer and use it in GitHub Desktop.
Handy dandy javascript formatting functions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
String.prototype.format = function () { | |
var re = /\{\d+\}/g, args = arguments; | |
return this.replace(re, function (x) {return args[x.match(/\d+/)]; }); | |
}; | |
// Number.toRad method | |
if (typeof(Number.prototype.toRad) === "undefined") { | |
Number.prototype.toRad = function() { | |
return this * Math.PI / 180; | |
} | |
} | |
if (typeof console === "undefined" || typeof console.log === "undefined") { | |
console = {} | |
console.log = function(msg) {/* Suppress console logs in bad browsers */}; | |
} | |
// Getting cookie values | |
function C$(fldNm) { | |
var reCookie = new RegExp("([;\\s]|^)" + fldNm + "=([^;]*)", "i"), | |
fldVal = reCookie.exec(document.cookie); | |
return (fldVal) ? unescape(fldVal[2]) : ""; | |
} | |
// Getting querystring values | |
function Q$(name) { | |
var reQs, val; | |
reQs = new RegExp("[\\?&]" + name + "=([^&#]*)", "i"); | |
val = reQs.exec(parent.location.search); | |
return (val) ? unescape(val[1]) : ""; | |
} | |
// Functions for mimicking Rails time_ago_in_words function | |
function distanceOfTimeInWords(to) { | |
var now = new Date(); | |
var distance_in_milliseconds = to - now; | |
var distance_in_minutes = Math.abs(distance_in_milliseconds / 60000); | |
var words = ""; | |
if (distance_in_minutes < 1) { | |
words = "seconds"; | |
} else if (distance_in_minutes < 2) { | |
words = "1 min"; | |
} else if (distance_in_minutes < 45) { | |
words = Math.round(distance_in_minutes) + " min"; | |
} else if (distance_in_minutes < 90) { | |
words = "1 hour"; | |
} else if (distance_in_minutes < 1440) { | |
words = Math.round(distance_in_minutes / 60) + " hours"; | |
} else if (distance_in_minutes < 2160) { | |
words = "1 day"; | |
} else if (distance_in_minutes < 43200) { | |
words = Math.round(distance_in_minutes / 1440) + " days"; | |
} else if (distance_in_minutes < 86400) { | |
words = "1 month"; | |
} else if (distance_in_minutes < 525600) { | |
words = Math.round(distance_in_minutes / 43200) + " months"; | |
} else if (distance_in_minutes < 1051200) { | |
words = "1 year"; | |
} else { | |
words = "over " + Math.round(distance_in_minutes / 525600) + " years"; | |
} | |
return words; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment