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-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 / remove-invalid-xml-characters.js
Last active March 30, 2024 10:19
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 / 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