Useful Javascript Snippets & Functions Megalist

js

Here’s a curated list of useful javascript functions and snippets I’ve collected throughout the years.

Standard Variables

Get and set standard window and document and set them as variables

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;

alert(x + ' × ' + y);

Strip Tags, but Javascript

This function uses regex to remove HTML from strings.

let new_string = string.replace(/(<([^>]+)>)/gi, "");

Convert a string to camelCase

Use String.prototype.match() to break the string into words using an appropriate regexp.

const toCamelCase = str => {
    let s =
        str &&
        str
            .match(
            /[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g
            )
        .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase())
        .join('');
    return s.slice(0, 1).toLowerCase() + s.slice(1);
};

Usage:

toCamelCase('some_database_field_name'); // 'someDatabaseFieldName'
toCamelCase('Some label that needs to be camelized');
// 'someLabelThatNeedsToBeCamelized'
toCamelCase('some-javascript-property'); // 'someJavascriptProperty'
toCamelCase('some-mixed_string with spaces_underscores-and-hyphens');
// 'someMixedStringWithSpacesUnderscoresAndHyphens'

Get URL

This little snippet will return the full URL path.

var url = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname + window.location.search

Validate Email

This uses reges to validate an email address.

function checkEmail(email) {
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
    if (!reg.test(email)) return false;
    return true;
}

Remove Duplicates from an arry

Here we remove duplicate items from an array. Compiled by Svein Petter Gjøby.

const array = [1, 1, 1, 3, 3, 2, 2];

// Method 1: Using a Set
const unique = [...new Set(array)];

// Method 2: Array.prototype.reduce
const unique = array.reduce((result, element) => {
  return result.includes(element) ? result : [...result, element];
}, []);

// Method 3: Array.prototype.filter
const unique = array.filter((element, index) => {
  return array.indexOf(element) === index;
});

Get URL

This function will round numbers to two decimal places, and ensure that the returned value has two decimal places. For example 12.006 will return 12.01, .3 will return 0.30, and 5 will return 5.00. From Chris Coyier’s site.

function CurrencyFormatted(amount) {
    var i = parseFloat(amount);
    if(isNaN(i)) { i = 0.00; }
    var minus = '';
    if(i < 0) { minus = '-'; }
    i = Math.abs(i);
    i = parseInt((i + .005) * 100);
    i = i / 100;
    s = new String(i);
    if(s.indexOf('.') < 0) { s += '.00'; }
    if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
    s = minus + s;
    return s;
}

Reload an iFrame

Force a frame to reload. This example uses jQuery.

$('iframe').attr('src', $('iframe').attr('src'));

Pretty much what the title says, this will make any external link on the page open in a new window; useful for content sites.

$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if(!a.test(this.href)) {
       $(this).click(function(event) {
           event.preventDefault();
           event.stopPropagation();
           window.open(this.href, '_blank');
       });
   }
});

Here’s some alternative methods of targeting external links with jQuery.

// Technique #1
$('a').filter(function() {
   return this.hostname && this.hostname !== location.hostname;
}).addClass("external");

// Technique #2
$.expr[':'].external = function(obj) {
    return !obj.href.match(/^mailto\:/) && (obj.hostname != location.hostname);
};
$('a:external').addClass('external');

// Technique #3
$('a:not([href^="http://your-website.com"]):not([href^="#"]):not([href^="/"])').addClass('external');

// Technique #4
$('a').each(function() {
   var a = new RegExp('/' + window.location.host + '/');
   if (!a.test(this.href)) {
       // This is an external link
   }
});

Fancy, styled console.logs

Make your console.log() output pop.

console.log("%cBuilt by 351 Studios", "background-color:#FFCD02;color:#333333;padding:0.3em 1em;font-weight:900;line-height:1.5em;font-size:2em;");

Run after Page has laoded

Force your function to run after page load.

if (window.attachEvent) {
    window.attachEvent('onload', yourFunctionName);
} else {
    if (window.onload) {
        var curronload = window.onload;
        var newonload = function(evt) {
            curronload(evt);
            yourFunctionName(evt);
        };
        window.onload = newonload;
    } else {
        window.onload = yourFunctionName;
    }
}

Does Element Have Class?

Use Element.classList and DOMTokenList.contains() to check if the element has the specified class.

const hasClass = (el, className) => el.classList.contains(className);

Usage:

hasClass(document.querySelector('p.classname'), 'classname'); // returns true

toggleClass, but Javascript

Toggles a class for an HTML element.

const toggleClass = (el, className) => el.classList.toggle(className);

Usage:

toggleClass(document.querySelector('p.classname'), 'classname');

addClass, but Javascript

A function to add a class to an element.

function addClass(id, new_class) {
    var i,
    n=0;

    new_class = new_class.split(",");

    for (i=0; i < new_class.length; i++) {
        if ((" " + document.getElementById(id).className + " ").indexOf(" " + new_class[i] + " ") == -1 ){
            document.getElementById(id).className+=" "+new_class[i];
            n++;
        }
    }

    return n;
}

Usage:

onclick="addClass('changeme', 'round')"

Force an element to autofocus once the page has loaded.

Straightforward HTML to force an input to be focused.

<textarea rows="10" cols="50" onclick="this.focus();this.select()" readonly="readonly">
   example text
</textarea>

Check if Array Contains X

See if a value is contained in an array.

/**
 * Array.prototype.[method name] allows you to define/overwrite an objects method
 * needle is the item you are searching for
 * this is a special variable that refers to "this" instance of an Array.
 * returns true if needle is in the array, and false otherwise
 */
Array.prototype.contains = function ( needle ) {
   for (i in this) {
       if (this[i] == needle) return true;
   }
   return false;
}

// Now you can do things like:
var x = Array();
if (x.contains('foo')) {
   // do something special
}

html_entities, but in Javascript

htmlentities() is a PHP function which converts special characters (like <) into their escaped/encoded values (like <). This allows you to show to display the string without the browser reading it as HTML.

function htmlEntities(str) {
    return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

Strip numbers from a string

Simple one liner to strip numbers from a string using regex.

newString = someString.replace(/[0-9]/g, '');

Is jQuery Loaded?

Sometimes you just need to check for jQuery with Javascript. Here’s a useful method:

if (typeof jQuery == 'undefined') {
    // jQuery IS NOT loaded, do stuff here.
}

Detect Touch

Detect whether the device has touch capabilities.

var hasTouch;
window.addEventListener('touchstart', function setHasTouch () {
    hasTouch = true;
    window.removeEventListener('touchstart', setHasTouch);
}, false);

Checks if the target value exists in a JSON object

Checks if keys is non-empty and use Array.prototype.every() to then check its keys to internal depth of the object.

const hasKey = (obj, keys) => {
  return (
    keys.length > 0 &&
    keys.every(key => {
      if (typeof obj !== 'object' || !obj.hasOwnProperty(key)) return false;
      obj = obj[key];
      return true;
    })
  );
};

GET Requests

Makes a GET request to the passed URL.

const httpGet = (url, callback, err = console.error) => {
    const request = new XMLHttpRequest();
    request.open('GET', url, true);
    request.onload = () => callback(request.responseText);
    request.onerror = () => err(request);
    request.send();
};

Usage:

httpGet(
  'https://urlgoeshere.com',
  console.log
);

POST Requests

Makes a POST request to the passed URL.

const httpPost = (url, data, callback, err = console.error) => {
    const request = new XMLHttpRequest();
    request.open('POST', url, true);
    request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
    request.onload = () => callback(request.responseText);
    request.onerror = () => err(request);
    request.send(data);
};

Usage:

const post = {
  user: 1,
  id: 222,
  title: 'Marko Bajlovic',
  body: 'Galaxies globular star cluster muse about the carbon in our apple pies two ghostly white figures in coveralls and helmets are soflty dancing courage of our questions.'
};
const data = JSON.stringify(post);

httpPost(
  'https://urlgoeshere.com',
  data,
  console.log
);

Enforce HTTPS with Javascript

Redirects the page to HTTPS if it’s currently in HTTP.

const httpsRedirect = () => {
    if (location.protocol !== 'https:')
        location.replace('https://' + location.href.split('//')[1]);
};

Usage:

httpsRedirect();

Insert HTML After Target Element

Inserts an HTML string after the end of the specified element.

const insertAfter = (el, htmlString) =>
    el.insertAdjacentHTML('afterend', htmlString);

Usage:

insertAfter(document.getElementById('myId'), '<p>after</p>');

Insert HTML Before Target Element

Inserts an HTML string before the start of the specified element.

const insertBefore = (el, htmlString) =>
    el.insertAdjacentHTML('beforebegin', htmlString);

Usage:

insertBefore(document.getElementById('myId'), '<p>before</p>');

Check if String is Alphanumeric

Inserts an HTML string before the start of the specified element.

const isAlphaNumeric = str => /^[a-z0-9]+$/gi.test(str);

Usage:

isAlphaNumeric('hello123'); // true
isAlphaNumeric('123'); // true
isAlphaNumeric('hello 123'); // false (space character is not alphanumeric)
isAlphaNumeric('#$hello'); // false

Slugify a String

Converts a string to a URL-friendly slug.

const slugify = str =>
    str
        .toLowerCase()
        .trim()
        .replace(/[^\w\s-]/g, '')
        .replace(/[\s_-]+/g, '-')
        .replace(/^-+|-+$/g, '');

Usage:

slugify('Hello World?'); // 'hello-world'

Pluralize

Returns the singular or plural form of the word based on the input number, using an optional dictionary if supplied.

const pluralize = (val, word, plural = word + 's') => {
    const _pluralize = (num, word, plural = word + 's') =>
        [1, -1].includes(Number(num)) ? word : plural;
    if (typeof val === 'object')
        return (num, word) => _pluralize(num, word, val[word]);
    return _pluralize(val, word, plural);
};

Usage:

pluralize(0, 'apple'); // 'apples'
pluralize(1, 'apple'); // 'apple'
pluralize(2, 'apple'); // 'apples'
pluralize(2, 'person', 'people'); // 'people'

const PLURALS = {
  person: 'people',
  radius: 'radii'
};
const autoPluralize = pluralize(PLURALS);
autoPluralize(2, 'person'); // 'people'

Run a Function X Times

Iterates over a callback n times

const times = (n, fn, context = undefined) => {
  let i = 0;
  while (fn.call(context, i) !== false && ++i < n) {}
};

Usage:

var output = '';
times(5, i => (output += i));
console.log(output); // 01234

Copy Text to Clipboard

Send a string to the clipboard.

function copyToClipboard() {
    const copyText = document.getElementById("myInput");
    copyText.select();
    document.execCommand("copy");
}

or

//new API
function copyToClipboard() {
    navigator.clipboard.writeText(document.querySelector('#myInput').value)
}

Fetch, with Error Handling

Break down a fetch step by step. If the response is good, the response will be returned as JSON. If a 404 or any non-network issue error occurs, the response code will be returned. Promises will be rejected and catched to (error => console.error(Fetch Error =\n, error))).

const fetch = require('node-fetch');

let multifetch = async () => {
    let urls = [
        "https://flathub.org/stats/52",
        "https://flathub.org/stats/2018/06/03.json",
        "https://flathub.org/stats/52",
        "https://flathub.org/stats/2018/06/03.json"
    ]

    // urls.map( e => fetch(e)
    //    .then(response => response.json()) // parses response to JSON
    //    .catch(error => console.error(`Fetch Error =\n`, error)))

    for (let e of urls) {
        fetch(e)
            .then(response => response.ok ? response : response.status) // parses response to JSON
            .then(res => console.log(res))
            .catch(error => console.error(`Fetch Error =\n`, error))
    }
}
multifetch();

// async/await version
let data = await fetch(url)
    .then(res => res.ok ? res : res.status)
    .catch(error => console.error(`Fetch Error =\n`, error));

Hope some of these you find useful on your programming travels.

ender