LANGUAGE » JAVASCRIPT » UTILS
Miscellaneous
JSON
js
// Object to JSON
var myObject = {field1: 'hello', field2: [1, 2, 3]};
var jsonString = JSON.stringify(myObject);
// JSON to Object
myObject = JSON.parse(jsonString);
Auto-scroll (no animation)
js
// Scroll body to element
var bodyElement = document.scrollingElement || document.body;
bodyElement.scrollTop = $('#element-id').offset().top;
// Scroll element with scroll to end
var tableElement = document.getElementById(elementId);
tableElement.scrollTop = tableElement.scrollHeight - tableElement.clientHeight;
Return new line according to OS
js
function newLine() {
if (window.navigator.userAgent.indexOf('Windows NT') !== -1) {
return '\r\n';
}
return '\n';
}
Save file generated by javascript
js
function saveTextFile(filename, content) {
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([content], {type: 'text/plain; charset=utf-8'});
window.navigator.msSaveOrOpenBlob(blob, filename);
}
else {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain; charset=utf-8,' + encodeURI(content));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
}
Parse HTML entities
js
function parseHtmlEntities(str) {
return str.replace(/&#([0-9]{1,3});/gi, function(match, numStr) {
var num = parseInt(numStr, 10);
return String.fromCharCode(num);
}).replace(/"/g, '"').replace(/&/g, '&');
}