Paulund
2023-01-01 #javascript

JavaScript Essentials: A Deep Dive into Useful Helper Functions

String Helpers

Capitalize First Letter Of String

This is take the first letter of the string and uppercase the letter. Then it will concatenate the rest of the string without the first letter.

const capitalize = (text) => `${text.charAt(0).toUpperCase()}${text.slice(1)}`;

ucfirst function

Camel Case A String

You can do this by using the below regex to select all the matched parts of the string and then on the first index you lowercase the word and on the next indexes you can make uppercase.

export const camel = (text: string)
:
string => {
    return text.replace(/(?:^\w|[A-Z]|\b\w|\s+)/g, function (match, index) {
        if (+match === 0) return ""; // if space
        return index === 0 ? match.toLowerCase() : match.toUpperCase();
    });
}

Camel Function

Check Number Is Odd Or Even

This is a quick little snippet which can prove to be quite useful. This snippet will check to see if a number is odd or even.

export const checkEven = (val) => (val % 2 === 0);

Is Numeric

export const isNumeric = (n) => !isNaN(parseFloat(n)) && isFinite(n);

Return Everything After The First Occurrence Of A String

This will allow you to pass in a string sentence and then a character and then it will return everything after the first occurrence of the character.

export const after = (text: string, afterText: string
):
string => text.split(afterText)[1] ?? ''

After Function

Return Everything Before The First Occurrence Of A String

This will allow you to pass in a string sentence and then a character and then it will return everything before the first occurrence of the character.

export const before = (text: string, beforeText: string
):
string => {
    const before = text.split(beforeText)[0];
    if (before === text) {
        return '';
    }

    return before;
}

Before Function

Return Everything Between Two Strings

This will allow you to pass in a string and then two characters and then it will return everything between the two characters.

export const between = (text: string, start: string, end: string
):
string => {
    const between = text.split(start).pop().split(end)[0];

    if (between === text) {
        return '';
    }

    return between;
}

Between Function

String Excerpt

This will allow you to create an excerpt from a string

export const excerpt = (text: string, length: number = 120, excerptSymbol: string = '...'
):
string =>
    `${text.substring(0, length)}${excerptSymbol}`

Excerpt Function

Is JSON

This will allow you to check if a string is valid JSON

export const isJson = (text: string)
:
boolean => {
    try {
        JSON.parse(text);
    } catch (e) {
        return false;
    }

    return true;
}

isJson Function

Is String

This will allow you to check if a value is a string

export const isString = (value: any)
:
boolean => typeof value === 'string' || value instanceof String;

IsString Function

Lowercase First Letter Of String

This will allow you to lowercase the first letter of a string

export const lcFirst = (text: string)
:
string => `${text.charAt(0).toLowerCase()}${text.slice(1)}`;

lcFirst Function

Limit String Length

This will allow you to limit the length of a string

export const limit = (text: string, length: number
):
string => text.substring(0, length)

Limit Function

Mask String

This will allow you to mask a string which can be used when displaying credit card numbers or other sensitive information.

export const mask = (str: string, show: number, mask: string = '*'
):
string => `${str}`.slice(-show).padStart(`${str}`.length, mask);

Mask Function

Remove Numbers From String

This will allow you to remove numbers from a string

export const removeNumbers = (text: string)
:
string => text.replace(/[0-9]/g, '')

removeNumbers Function

Remove Special Characters From String

This will allow you to remove special characters from a string

export const removeSpecialCharacters = (text: string)
:
string => text.replace(/[^a-zA-Z0-9 ]/g, '')

removeSpecialCharacters Function

Remove Spaces From String

This will allow you to remove spaces from a string

export const removeSpaces = (text: string)
:
string => text.replace(/\s/g, '')

removeSpaces Function

Reverse A String

This will allow you to reverse a string

export const reverse = (str: string)
:
string => str.split('').reverse().join('')

Reverse Function

Slugify A String

This will allow you to slugify a string to use in urls

export const slug = (text: string)
:
string => text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '');            // Trim - from end of text

Slug Function

Snake Case A String

This will allow you to snake case a string this will change this is the text to snake case! to this_is_the_text_to_snake_case

export const snake = (str: string)
:
string =>
    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.toLowerCase())
        .join('_');

Snake Function

Title Case A String

This will allow you to title case a string this will change this is the text to title case! to This Is The Text To Title Case!

export const title = (str: string)
:
string =>
    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.charAt(0).toUpperCase() + x.slice(1))
        .join(' ');

Title Function

Uppercase First Letter Of Each Word In String

This will allow you to uppercase the first letter of each word in a string

export const ucwords = (text: string)
:
string => text.toLocaleLowerCase()
    .replace(/(?<= )[^\s]|^./g, str => str.toLocaleUpperCase())

ucwords Function

Count Words In A String

This will allow you to count the number of words in a string

export const wordCount = (text: string)
:
number => text.trim().split(' ').length;

wordCount Function

Array Helpers

Check If Array Is Empty

const isEmpty = (arr) => Array.isArray(arr) && arr.length === 0;

isEmpty([1, 2, 3]); // Result: false
isEmpty([]);// Result: true

isEmpty

Check If Array Is Not Empty

const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;

isNotEmpty([1, 2, 3]); // Result: true
isNotEmpty([]);// Result: false

isNotEmpty

Check If Array Is Empty Or Undefined

const isEmptyOrUndefined = (arr) => arr === undefined || (Array.isArray(arr) && arr.length === 0);

Get Unique Values From Array

There are a few ways this can be done some of the most common ways are to use JavaScript array functions such as map and filter. But as of ES6 a object called Set was introduced which allows you to store a collection of unique value of any type.

This can be used in line with the spread operator to return the values of an array.

const unique = (arr) => [...new Set(arr)];

Unique Function

GroupBy Function

This is a helper function you can use to take an array and group by a key.

export const groupBy = (data, key) => {
    return data.reduce(function (carry, el) {
        const group = el[key];

        if (carry[group] === undefined) {
            carry[group] = []
        }

        carry[group].push(el)
        return carry
    }, {})
}

You can use this on your arrays by passing in your array with the key you want to group on.

let array = [
    {name: "Name 1", value: 15},
    {name: "Name 1", value: 30},
    {name: "Name 2", value: 45},
    {name: "Name 2", value: 70}
]

console.log(groupBy(array, 'name'))

This will output the new array as

[
    "Name 1"
:
[
    {name: "Name 1", value: 15},
    {name: "Name 1", value: 30},
],
    "Name 2"
:
[
    {name: "Name 2", value: 45},
    {name: "Name 2", value: 70}
],
]

Chunk Array

This will allow you to chunk an array into smaller arrays.

export const chunk = (array, size) => {
    const result = [];
    for (let i = 0; i < array.length; i += size) {
        result.push(array.slice(i, i + size));
    }
    return result;
}

Chunk Function

Difference Between Two Arrays

This will allow you to get the difference between two arrays.

export const diff = (a, b) => {
    const s = new Set(b);
    return a.filter(x => !s.has(x));
}

Diff Function

Date Helpers

Check If Date Is Daylight Savings Time

export const isDaylightSavingsTime = (date) => {
    const january = new Date(date.getFullYear(), 0, 1);
    const july = new Date(date.getFullYear(), 6, 1);
    return Math.min(january.getTimezoneOffset(), july.getTimezoneOffset()) === date.getTimezoneOffset();
}

Day light Savings Function

URL Helpers

Is Valid URL

Using the URL object wrapped in a try...catch statement we can check if a string is a valid URL.

export const isValidUrl = (url) => {
    try {
        new URL(url);
        return true;
    } catch (e) {
        return false;
    }
}

Get Query String From URL

export const urlQueryString = (url) => {
    const questionMarkIndex = url.indexOf('?');
    return questionMarkIndex === -1 ? '' : url.slice(questionMarkIndex + 1);
}

Get Protocol From URL

export const urlProtocol = (url) => {
    const colonIndex = url.indexOf(':');
    return colonIndex === -1 ? '' : url.slice(0, colonIndex);
}

Get Host From URL

export const urlHost = (url) => {
    const hostStart = url.indexOf('//') + 2;
    const hostEnd = url.indexOf('/', hostStart);
    return hostEnd === -1 ? url.slice(hostStart) : url.slice(hostStart, hostEnd);
}

Get Domain From URL

export const urlDomain = (url) => {
    const host = urlHost(url);
    const parts = host.split('.');
    const partsCount = parts.length;
    if (partsCount === 1) {
        return host;
    }
    return parts[partsCount - 2] + '.' + parts[partsCount - 1];
}

Get Pathname From URL

export const urlPathname = (url) => {
    const hostStart = url.indexOf('//') + 2;
    const hostEnd = url.indexOf('/', hostStart);
    const questionMarkIndex = url.indexOf('?');
    return questionMarkIndex === -1
        ? url.slice(hostEnd)
        : url.slice(hostEnd, questionMarkIndex);
}

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

Get 50% off forever using the code 50OFFUP.