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)}`;
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();
});
}
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] ?? ''
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;
}
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;
}
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}`
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;
}
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;
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)}`;
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)
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);
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, '')
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, '')
Reverse A String
This will allow you to reverse a string.
export const reverse = (str: string): string => str.split('').reverse().join('')
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
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('_');
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(' ');
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())
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;
Check If Array Is Empty
const isEmpty = (arr) => Array.isArray(arr) && arr.length === 0;
isEmpty([1, 2, 3]); // Result: false
isEmpty([]);// Result: true
Check If Array Is Not Empty
const isNotEmpty = (arr) => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]); // Result: true
isNotEmpty([]);// Result: false
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)];
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;
}
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));
}
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();
}
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;
}
}
Originally published at https://paulund.co.uk.