Super Useful Javascript Functions/Code Snippets

Not all of these functions are one-liners, but most of them are pretty damn compact (and useful).

Most are derived from StackOverflow.

Validate an email address

function validateEmail(email) {
var re = /\S+@\S+\.\S+/;
return re.test(email);
}

Get a random color

function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}

Return a random element from an array

function randomElement() {
var element = arr[Math.floor(Math.random()*arr.length)];
return item;
}

Remove a particular element from an array

var arr = [4, 5, 6];
var index = array.indexOf(5);

if (index > -1) {
arr.splice(index, 1);
}

Get a query string in Javascript

function getParameterByName(name, url) {
if (!url) {
url = window.location.href;
}
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}

Usage:

// query string: ?foo=lorem&bar=&baz
var foo = getParameterByName('foo'); // "lorem"
var bar = getParameterByName('bar'); // "" (present with empty value)
var baz = getParameterByName('baz'); // "" (present with no value)
var qux = getParameterByName('qux'); // null (absent)

Convert the first letter of a string to uppercase

function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}

Replace all occurrences in a string

function replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}

Insert an item into an array at a specific index

arr.splice(index, 0, item);

Example:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join());
arr.splice(2, 0, "Lene");
console.log(arr.join());