Last active
May 14, 2019 16:46
-
-
Save iamaamir/34c516aaed874ceb8f039783ac0201e2 to your computer and use it in GitHub Desktop.
js helper functions
This file contains 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
// Date object to unix timestamp | |
function unix(date) { | |
return Math.round(date.getTime() / 1000); | |
} | |
// replace all from string | |
String.prototype.replaceAll = function(rgx, replacement) { | |
var self = this; | |
return self.replace(new RegExp(rgx, "g"), replacement); | |
}; | |
// download file from api response | |
function downloadCSV(data, fileName) { | |
var a = document.createElement("a"); | |
document.body.appendChild(a); | |
a.style = "display: none"; | |
var blob = new Blob([data], { type: "octet/stream" }), | |
url = window.URL.createObjectURL(blob); | |
a.href = url; | |
a.download = fileName; | |
a.click(); | |
window.URL.revokeObjectURL(url); | |
} | |
// random number in a specific range | |
function range(min, max) { | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
// escape HTML | |
function escapeHTML(text) { | |
var replacements = { "<": "<", ">": ">", "&": "&", "": """ }; | |
return text.replace(/[<>&"]/g, function(character) { | |
return replacements[character]; | |
}); | |
} | |
// escape regex specific chars | |
function escapeRegExp(str) { | |
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); | |
} | |
// returns an array of the given len with numbers | |
function arr(len){ | |
return Array(len).fill().map((_,i) => i) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment