Skip to content

Instantly share code, notes, and snippets.

View john-doherty's full-sized avatar
🎯
Focusing

John Doherty john-doherty

🎯
Focusing
View GitHub Profile
@john-doherty
john-doherty / javascript-trim-svg-whitespace.js
Created October 21, 2016 13:39
Trim whitespace from SVG elements
function trimSvgWhitespace() {
// get all SVG objects in the DOM
var svgs = document.getElementsByTagName("svg");
// go through each one and add a viewbox that ensures all children are visible
for (var i=0, l=svgs.length; i<l; i++) {
var svg = svgs[i],
box = svg.getBBox(), // <- get the visual boundary required to view all children
@john-doherty
john-doherty / remove-invalid-xml-characters.js
Last active September 23, 2024 07:38
JavaScript function that removes invalid XML characters from a string according to the spec
/**
* Removes invalid XML characters from a string
* @param {string} str - a string containing potentially invalid XML characters (non-UTF8 characters, STX, EOX etc)
* @param {boolean} removeDiscouragedChars - should it remove discouraged but valid XML characters
* @return {string} a sanitized string stripped of invalid XML characters
*/
function removeXMLInvalidChars(str, removeDiscouragedChars) {
// remove everything forbidden by XML 1.0 specifications, plus the unicode replacement character U+FFFD
var regex = /((?:[\0-\x08\x0B\f\x0E-\x1F\uFFFD\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]))/g;
@john-doherty
john-doherty / add-query-params-to-url.js
Last active August 18, 2024 00:55
Add query string parameters to a URL in JavaScript (works with browser/node, merges duplicates and works with absolute and relative URLs)
/**
* Adds query params to existing URLs (inc merging duplicates)
* @param {string} url - src URL to modify
* @param {object} params - key/value object of params to add
* @example
* // returns /guides?tag=api
* addQueryParamsToUrl('/guides?tag=hardware', { tag:'api' })
* @example
* // returns https://orcascan.com/guides?tag=api
* addQueryParamsToUrl('https://orcascan.com/guides?tag=hardware', { tag: 'api' })
@john-doherty
john-doherty / url-to-filename.js
Last active May 23, 2024 13:49
Convert a URL into a readable filename safe string
/**
* Convert a URL into a readable filename safe string
* - sort query params
* - remove protocol
* - replace / with !
* - replace ? with !!
* - replace remaining illegal characters with -
* @example
* INPUT: convertUrlToReadableFilename('https://orcascan.com/guides/how-to-scan-barcodes-into-microsoft-excel-59fd67f9');
@john-doherty
john-doherty / settimeout-using-requestanimationframe.js
Created April 24, 2018 17:54
JavaScript window.setTimeout replacement using requestAnimationFrame for better performance
(function (window) {
'use strict';
var oldSetTimeout = window.setTimeout;
/**
* Behaves the same as setTimeout but uses requestAnimationFrame() for better performance
* @param {function} fn The callback function
* @param {int} delay The delay in milliseconds
@john-doherty
john-doherty / javascript-clean-csv-string.js
Last active March 28, 2024 01:31
Remove empty values, trim whitespace and removes duplicate from a comma separated string in JavaScript
/**
* Removes empty values, trims whitespace and removes duplicate from a comma separated string in JavaScript
* @example
* cleanCsvString('one, ,, , two,two,two, three'); // returns 'one,two,three'
* cleanCsvString('one, ,, , two,two,two, three', false); // returns 'one,two,two,two,three'
* @param {string} str - string to modify
* @param {boolean} removeDuplicates - should remove duplicate items? (default = true)
* @returns {string} cleaned CSV string
*/
function cleanCsvString(str, removeDuplicates) {
@john-doherty
john-doherty / disable-mac-swipe-navigation.js
Created February 12, 2018 11:42
Disable Mac swipe navigation in pure JavaScript
(function (window) {
if ((/Macintosh/gi).test(navigator.userAgent) && (/Chrome|Safari|Firefox/gi).test(navigator.userAgent)) {
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
}
@john-doherty
john-doherty / local-storage-helper.js
Last active March 10, 2024 19:41
localStorage helper (takes care of casting types)
/**
* local storage helper (takes care of casting types)
*/
var localStorageHelper = {
/**
* Check if item exists in local storage.
* @param {string} key - variable name
* @return {boolean} true if key exists, otherwise false
*/
@john-doherty
john-doherty / cordova-file-storage.js
Last active August 2, 2023 10:32
An easy way to read/write files in Cordova
var fileStorage = {
/**
* Saves a file on the device
* @param {string} name - filename (can include sub folders)
* @param {string} data - file contents
* @param {boolean} useSandbox - uses protected sandbox if true, otherwise external (default false)
* @returns {Promise} executes .then with saved file path as first param
*/
write: function (name, data, useSandbox) {
@john-doherty
john-doherty / javascript-wait-for-events.js
Last active May 31, 2023 11:19
Wait for multiple JavaScript events to fire
/**
* Waits for multiple DOM events to fire
* @example
* waitForEvents(window, [
* 'DOMContentLoaded',
* 'online'
* ])
* .then(function(result) {
* // do stuff