Skip to content

Instantly share code, notes, and snippets.

@clovis-junior
Last active May 4, 2026 16:43
Show Gist options
  • Select an option

  • Save clovis-junior/3b357eda0edd3b5120219140a4afff62 to your computer and use it in GitHub Desktop.

Select an option

Save clovis-junior/3b357eda0edd3b5120219140a4afff62 to your computer and use it in GitHub Desktop.
I made a simple Javascript functions to agilize programming work. I using this on my own projects! And i very appreciate your comments from this gist πŸ––πŸ»
/**
* ********************************************************
* Javascript Utilities
* ********************************************************
* @author Clovis Junior <https://github.com/clovis-junior>
* @version 2.0
* @license GNU General Public License v2 or later
* ********************************************************
*/
function slugfy(string, separator = '-') {
return String(value ?? '')
.trim()
.normalize('NFKD')
.replace(/[\u0300-\u036F]/g, '')
.toLowerCase()
.replace(/[^a-z0-9\s-]/g, '')
.replace(/\s+/g, separator)
.replace(new RegExp(String.raw`[\s${separator}]+`, 'g'), separator)
}
function captalize(string) {
string = String(string ?? '');
return `${string.charAt(0).toUpperCase()}${string.toLowerCase().slice(1)}`
}
function addZero(number) {
return String(number).padStart(2, '0');
}
function isString(variable) {
return (typeof variable === 'string' || variable instanceof String);
}
function isEmpty(variable) {
return (typeof variable === 'undefined' || variable === null ||
(typeof variable === 'string' && variable.trim().length <= 0) ||
(Array.isArray(variable) && variable.length <= 0) ||
(variable instanceof Object && Object.keys(variable).length <= 0))
}
function htmlEncode(string) {
string = String(string ?? '');
return string.replace(/[&<>"']/g, function (e) {
return `&#${e.charCodeAt(0)};`
})
}
function generateRandomString(length = 8, uppercase = true, numbers = true, special = false) {
let chars = 'abcdefghijklmnopqrstuvwxyz';
if (uppercase) chars += 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if (numbers) chars += '0123456789';
if (special) chars += '!@#$%&*';
if (!chars.length || length <= 0) return '';
const array = new Uint32Array(length);
crypto.getRandomValues(array);
return Array.from(array, n => chars[n % chars.length]).join('');
}
//---------------- URL Parameters --------------------//
function getURLParams(path = window.location.href) {
const queryString = path.includes('?')
? path.split('?')[1].replace(/#/g, '&')
: path.replace(/#/g, '&');
const searchParams = new URLSearchParams(queryString);
return {
get data() {
return Object.fromEntries(searchParams.entries());
},
list() {
return Object.fromEntries(searchParams.entries());
},
set(param, value) {
return searchParams[param] = value;
},
get(param) {
return searchParams.get(param) ?? null;
},
has(param) {
return searchParams.has(param);
},
delete(param) {
searchParams.delete(param);
},
toString() {
return searchParams.toString();
}
};
}
//---------------- Validators --------------------//
function urlCheck(value) {
let filter = /^(https?)\:\/\/(?:www\.)?([a-zA-Z0-9-:]{1,256})\.([a-zA-Z0-9.]{2,})\b([a-zA-Z0-9-_()@:%\+.~#?&\/\/=]*)$/is;
return (filter.test(value)) ? true : false;
}
function emailCheck(value) {
let filter = /^([\w-]+(?:\.[\w-]+)*)\@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/is;
return (filter.test(value)) ? true : false;
}
function phoneNumberCheck(value) {
let filter = /^(\+\d{1,2})?(?:\-|\s)?\(?0?(\d{2})\)?(?:\-|\s)?((\d{1})?(?:\-|\.|\s)?\d{4}(?:\-|\.|\s{1})?\d{4})$/s;
return (filter.test(value)) ? true : false;
}
//---------------- Cookies --------------------//
function setCookie(name, value, expires = 0, path = '/') {
if (typeof name !== 'string' || typeof expires !== 'number') return;
const date = new Date();
if (expires > 0)
date.setTime(date.getTime() + expires * 24 * 60 * 60 * 1000);
else
date.setTime(new Date('2038-01-19T03:14:08Z').getTime());
document.cookie = [
`${encodeURIComponent(name)}=${encodeURIComponent(String(value ?? ''))}`,
`expires=${date.toUTCString()}`,
`path=${path}`,
'SameSite=Lax'
].join(';');
}
function getCookie(name) {
if (typeof name !== 'string') return '';
const encodedName = encodeURIComponent(name) + '=';
const cookies = document.cookie.split(';');
for (const cookie of cookies) {
const item = cookie.trim();
if (item.startsWith(encodedName))
return decodeURIComponent(item.slice(encodedName.length));
}
return ''
}
function hasCookie(name) {
let cookie = getCookie(name);
return (cookie.length > 0)
}
function deleteCookie(name, path) {
if (!hasCookie(name))
return;
document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=${path}`;
}
//---------------- Loaders --------------------//
function loadStyle(href, rel = 'stylesheet', crossOrigin = 'anonymous', callback) {
let link = document.createElement('link');
link.rel = rel.toString();
link.href = href.toString();
link.crossOrigin = crossOrigin.toString();
link.onload = function () {
if (typeof callback === 'function')
return callback();
};
document.head.appendChild(link)
}
function loadScript(source, callback) {
let script = document.createElement('script');
script.src = source.toString();
script.onload = function () {
if (typeof callback === 'function')
return callback();
};
document.head.appendChild(script)
}
function loadImages(callback) {
const images = document.querySelectorAll('img[data-async-src]');
if (pending <= 0) {
if (typeof callback === 'function') callback();
return;
}
images.forEach(element => {
const image = new Image();
image.onload = function (e) {
const aspect = Math.abs(image.width / image.height);
element.width = element.clientWidth || image.width;
element.height = Math.ceil(element.width / aspect) || image.height;
element.src = e.target.src;
element.removeAttribute('data-async-src');
},
image.onabort = image.onerror = function (e) {
element.remove()
};
image.src = element.getAttribute('data-async-src');
})
return (typeof callback === 'function') ? callback() : false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment