Checkout the original post to read with Table of Contents
Learn React with The Complete React Bootcamp only for $49 a year (Free 1 month trial) *affiliate link
Utility functions are like shortcuts for your code. They let you handle things like arrays, dates, and strings without writing a lot of extra code. Instead of doing the same tasks over and over, you can use these functions to get the job done faster, consistent and prevent errors.
In this article, we'll look at 37 common JavaScript utility functions that every developer should know. If you're new to JavaScript or haven't documented your own utility functions, this article is for you. By learning and using these utilities, you'll save time, reduce errors, and gain a deeper understanding of how to write clean, reusable code.
Related posts
So, let's get started and see how these utilities can make your JavaScript coding easier and more effective.
Sure! Here is a list of common JavaScript utility functions for working with strings, each with a short explanation and example usage:
Removes whitespace from both ends of a string.
function trim(str) { return str.trim(); } // Example usage console.log(trim(' Hello World! ')); // 'Hello World!'
Capitalizes the first letter of a string.
function capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); } // Example usage console.log(capitalize('hello')); // 'Hello'
Converts a string with hyphens to camel case (camelCase).
function toCamelCase(input) { return ( input // Replace kebab-case, snake_case, and spaces with a space .replace(/[-_\s]+(.)?/g, (_, char) => (char ? char.toUpperCase() : '')) // Handle PascalCase .replace(/^[A-Z]/, (char) => char.toLowerCase()) ); } // Test cases console.log(toCamelCase('PascalCase')); // pascalCase console.log(toCamelCase('kebab-case-string')); // kebabCaseString console.log(toCamelCase('snake_case_string')); // snakeCaseString console.log(toCamelCase('string with spaces')); // stringWithSpaces
Converts a string to kebab case (kebab-case).
function toKebabCase(input) { return ( input // Handle camelCase and PascalCase by inserting a dash before uppercase letters .replace(/([a-z])([A-Z])/g, '$1-$2') // Replace underscores and spaces with dashes .replace(/[_\s]+/g, '-') // Convert the entire string to lowercase .toLowerCase() ); } // Test cases console.log(toKebabCase('camelCase')); // camel-case console.log(toKebabCase('PascalCase')); // pascal-case console.log(toKebabCase('snake_case_string')); // snake-case-string console.log(toKebabCase('string with spaces')); // string-with-spaces
Converts a string to snake case (snake_case).
function toSnakeCase(input) { return ( input // Handle camelCase and PascalCase by inserting an underscore before uppercase letters .replace(/([a-z])([A-Z])/g, '$1_$2') // Replace dashes and spaces with underscores .replace(/[-\s]+/g, '_') // Convert the entire string to lowercase .toLowerCase() ); } // Test cases console.log(toSnakeCase('camelCase')); // camel_case console.log(toSnakeCase('PascalCase')); // pascal_case console.log(toSnakeCase('kebab-case-string')); // kebab_case_string console.log(toSnakeCase('string with spaces')); // string_with_spaces
Converts a string to pascal case (PascalCase).
function toPascalCase(input) { return ( input // Replace camelCase, kebab-case, snake_case, and spaces with a space .replace(/([a-z])([A-Z])|[-_\s]+(.)?/g, (match, p1, p2, p3) => { if (p2) { return p1 + ' ' + p2; } return p3 ? ' ' + p3.toUpperCase() : ''; }) // Split by space, capitalize first letter of each word, and join .split(' ') .map((word) => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()) .join('') ); } // Test cases console.log(toPascalCase('camelCase')); // CamelCase console.log(toPascalCase('kebab-case-string')); // KebabCaseString console.log(toPascalCase('snake_case_string')); // SnakeCaseString console.log(toPascalCase('string with spaces')); // StringWithSpaces
Checks if a string contains a specified substring.
function contains(str, substring) { return str.indexOf(substring) !== -1; } // Example usage console.log(contains('Hello World', 'World')); // true
Replaces all occurrences of a substring within a string.
function replaceAll(str, find, replace) { return str.split(find).join(replace); } // Example usage console.log(replaceAll('Hello World', 'o', 'a')); // 'Hella Warld'
Pads the start of a string with another string until the target length is reached.
function padStart(str, targetLength, padString) { return str.padStart(targetLength, padString); } // Example usage console.log(padStart('5', 3, '0')); // '005'
Pads the end of a string with another string until the target length is reached.
function padEnd(str, targetLength, padString) { return str.padEnd(targetLength, padString); } // Example usage console.log(padEnd('5', 3, '0')); // '500'
Counts the number of times a character appears in a string.
function countOccurrences(str, char) { return str.split(char).length - 1; } // Example usage console.log(countOccurrences('Hello World', 'o')); // 2
Escapes HTML special characters to prevent XSS attacks.
function escapeHTML(str) { return str.replace(/[&<>"']/g, function (match) { const escapeChars = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }; return escapeChars[match]; }); } // Example usage console.log(escapeHTML('<div>"Hello" & \'World\'</div>')); // '<div>"Hello" & 'World'</div>'
Unescapes HTML special characters.
function unescapeHTML(str) { return str.replace(/&|<|>|"|'/g, function (match) { const unescapeChars = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'" }; return unescapeChars[match]; }); } // Example usage console.log(unescapeHTML('<div>"Hello" & 'World'</div>')); // '<div>"Hello" & \'World\'</div>'
Formats a number as a currency string, with commas as thousands separators.
function formatMoney(amount, decimalCount = 2, decimal = '.', thousands = ',') { try { // Ensure the amount is a number and fix the decimal places decimalCount = Math.abs(decimalCount); decimalCount = isNaN(decimalCount) ? 2 : decimalCount; const negativeSign = amount < 0 ? '-' : ''; let i = parseInt((amount = Math.abs(Number(amount) || 0).toFixed(decimalCount))).toString(); let j = i.length > 3 ? i.length % 3 : 0; return ( negativeSign + (j ? i.substr(0, j) + thousands : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousands) + (decimalCount ? decimal + Math.abs(amount - i) .toFixed(decimalCount) .slice(2) : '') ); } catch (e) { console.log(e); } } // Test cases console.log(formatMoney(1234567.89)); // 1,234,567.89 console.log(formatMoney(1234567.89, 3)); // 1,234,567.890 console.log(formatMoney(-1234567.89, 2, '.', ',')); // -1,234,567.89 console.log(formatMoney(1234567.89, 0, '.', ',')); // 1,234,568 console.log(formatMoney(1234.56, 2, ',', '.')); // 1.234,56
Truncates a paragraph to a specified length and adds an ellipsis if truncated.
function truncateParagraph(paragraph, maxLength) { if (paragraph.length <= maxLength) { return paragraph; } return paragraph.slice(0, maxLength) + '...'; } // Example usage const paragraph = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae eros eget tellus tristique bibendum. Donec rutrum sed sem quis venenatis.'; console.log(truncateParagraph(paragraph, 50)); // 'Lorem ipsum dolor sit amet, consectetur adipiscing...' console.log(truncateParagraph(paragraph, 100)); // 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent vitae eros eget tellus tristique b...'
If you want truncate string for styling purpose, you can do this with Tailwindcss truncate / line-clamp
Checks if a value is an object.
function isObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); } console.log(isObject({ a: 1 })); // true console.log(isObject([1, 2, 3])); // false
Merges two or more objects into one.
function mergeObjects(...objs) { return Object.assign({}, ...objs); } console.log(mergeObjects({ a: 1 }, { b: 2 }, { a: 3 })); // { a: 3, b: 2 }
Deeply merges two or more objects.
function deepMerge(...objects) { const isObject = (obj) => obj && typeof obj === 'object'; return objects.reduce((prev, obj) => { Object.keys(obj).forEach((key) => { const prevVal = prev[key]; const objVal = obj[key]; if (Array.isArray(prevVal) && Array.isArray(objVal)) { prev[key] = prevVal.concat(...objVal); } else if (isObject(prevVal) && isObject(objVal)) { prev[key] = deepMerge(prevVal, objVal); } else { prev[key] = objVal; } }); return prev; }, {}); } const obj1 = { a: 1, b: { x: 10 } }; const obj2 = { b: { y: 20 }, c: 3 }; console.log(deepMerge(obj1, obj2)); // { a: 1, b: { x: 10, y: 20 }, c: 3 }
Creates a deep clone of an object.
function deepClone(obj) { return JSON.parse(JSON.stringify(obj)); } const original = { a: 1, b: { c: 2 } }; const clone = deepClone(original); clone.b.c = 3; console.log(original.b.c); // 2 console.log(clone.b.c); // 3
Check The Right Way to Clone Nested Object/Arrayin Javascript for more advanced use case.
Returns a new object with specified keys omitted.
function omitKeys(obj, keys) { const result = { ...obj }; keys.forEach((key) => delete result[key]); return result; } console.log(omitKeys({ a: 1, b: 2, c: 3 }, ['a', 'c'])); // { b: 2 }
Returns a new object with only the specified keys.
function pickKeys(obj, keys) { const result = {}; keys.forEach((key) => { if (obj.hasOwnProperty(key)) { result[key] = obj[key]; } }); return result; } console.log(pickKeys({ a: 1, b: 2, c: 3 }, ['a', 'c'])); // { a: 1, c: 3 }
Inverts the keys and values of an object.
function invertObject(obj) { const result = {}; Object.keys(obj).forEach((key) => { result[obj[key]] = key; }); return result; } console.log(invertObject({ a: 1, b: 2, c: 3 })); // { '1': 'a', '2': 'b', '3': 'c' }
Checks if an object is empty (has no enumerable properties).
function isEmptyObject(obj) { return Object.keys(obj).length === 0; } console.log(isEmptyObject({})); // true console.log(isEmptyObject({ a: 1 })); // false
Creates a new object with the same keys but with values transformed by a function. Similar to array.map(), but for object
function mapObject(obj, fn) { const result = {}; Object.keys(obj).forEach((key) => { result[key] = fn(obj[key], key); }); return result; } console.log(mapObject({ a: 1, b: 2, c: 3 }, (value) => value * 2)); // { a: 2, b: 4, c: 6 }
Creates a new object with only the properties that pass a filter function. Similar to array.filter(), but for object
function filterObject(obj, fn) { const result = {}; Object.keys(obj).forEach((key) => { if (fn(obj[key], key)) { result[key] = obj[key]; } }); return result; } console.log(filterObject({ a: 1, b: 2, c: 3 }, (value) => value > 1)); // { b: 2, c: 3 }
Freezes an object, making it immutable.
function freezeObject(obj) { return Object.freeze(obj); } const obj = { a: 1, b: 2 }; const frozenObj = freezeObject(obj); frozenObj.a = 3; // Will not change the value console.log(frozenObj.a); // 1
Deeply freezes an object, making it and all nested objects immutable.
function deepFreeze(obj) { Object.keys(obj).forEach((name) => { const prop = obj[name]; if (typeof prop == 'object' && prop !== null) { deepFreeze(prop); } }); return Object.freeze(obj); } const obj = { a: 1, b: { c: 2 } }; deepFreeze(obj); obj.b.c = 3; // Will not change the value console.log(obj.b.c); // 2
Removes duplicate values from an array.
function uniqueArray(arr) { return [...new Set(arr)]; } console.log(uniqueArray([1, 2, 2, 3, 4, 4, 5])); // [1, 2, 3, 4, 5]
Splits an array into chunks of specified size.
function chunkArray(arr, size) { const result = []; for (let i = 0; i < arr.length; i += size) { result.push(arr.slice(i, i + size)); } return result; } console.log(chunkArray([1, 2, 3, 4, 5], 2)); // [[1, 2], [3, 4], [5]]
Returns the difference between two arrays.
function arrayDifference(arr1, arr2) { return arr1.filter((item) => !arr2.includes(item)); } console.log(arrayDifference([1, 2, 3], [2, 3, 4])); // [1]
These utility functions can help you perform various date manipulations and formatting tasks in JavaScript efficiently.
Formats a date into a specified string format.
function formatDate(date, format) { const map = { mm: ('0' + (date.getMonth() + 1)).slice(-2), dd: ('0' + date.getDate()).slice(-2), yyyy: date.getFullYear(), hh: ('0' + date.getHours()).slice(-2), MM: ('0' + date.getMinutes()).slice(-2), ss: ('0' + date.getSeconds()).slice(-2) }; return format.replace(/mm|dd|yyyy|hh|MM|ss/gi, (matched) => map[matched]); } const date = new Date(); console.log(formatDate(date, 'dd-mm-yyyy hh:MM:ss')); // Example: 28-07-2024 14:30:45
Adds a specified number of days to a date.
function addDays(date, days) { const result = new Date(date); result.setDate(result.getDate() + days); return result; } const date = new Date(); console.log(addDays(date, 5)); // Adds 5 days to the current date
Subtracts a specified number of days from a date.
function subtractDays(date, days) { const result = new Date(date); result.setDate(result.getDate() - days); return result; } const date = new Date(); console.log(subtractDays(date, 5)); // Subtracts 5 days from the current date
Calculates the number of days between two dates.
function daysBetween(date1, date2) { const oneDay = 24 * 60 * 60 * 1000; // hours * minutes * seconds * milliseconds const diffDays = Math.round(Math.abs((date2 - date1) / oneDay)); return diffDays; } const date1 = new Date('2024-07-01'); const date2 = new Date('2024-07-28'); console.log(daysBetween(date1, date2)); // Example: 27 days
Checks if a given date falls on a weekend.
function isWeekend(date) { const day = date.getDay(); return day === 0 || day === 6; } const date = new Date(); console.log(isWeekend(date)); // Returns true if the date is a weekend, otherwise false
Gets the number of days in a specific month of a specific year.
function getDaysInMonth(month, year) { return new Date(year, month + 1, 0).getDate(); } const month = 6; // July const year = 2024; console.log(getDaysInMonth(month, year)); // Example: 31 days in July 2024
function getDuration(startDate, endDate) { const diff = endDate - startDate; return Math.floor(diff / (1000 * 60 * 60)); // 1000 * 60 * 60 for duration in hours // 1000 * 60 * 60 * 24 for duration in days // 1000 * 60 for duration in minutes } const startDate = new Date('2024-07-01T12:00:00'); const endDate = new Date('2024-07-01T15:30:00'); console.log(getDurationInHours(startDate, endDate)); // Duration in hours
For more advance use-cases and tested utils for Date, consider using date library like day.js
We've covered 37 useful JavaScript utility functions that can help you code more efficiently. These functions simplify tasks like array handling, date formatting, and string manipulation. Using them can save you time and reduce errors in your code.
If this article was helpful, please share it with others who might benefit from it. Bookmark it for future reference, and if you have any favorite utility functions that weren't mentioned, feel free to share them in the comments.
Happy coding!
위 내용은 문자열, 객체, 배열 및 날짜에 대한 일반적인 JavaScript 유틸리티 함수의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!