logo 30 seconds of code Curated collection of useful JavaScript snippets that you can understand in 30 seconds or less.



String

byteSize

Returns the length of a string in bytes.

Convert a given string to a Blob Object and find its size.

以字节为单位返回字符串的长度。

将给定的字符串转换为[Blob Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob)并找到它的size

const byteSize = str => new Blob([str]).size;
byteSize('😀'); // 4
byteSize('Hello World'); // 11

capitalize

Capitalizes the first letter of a string.

Use array destructuring and String.prototype.toUpperCase() to capitalize first letter, ...rest to get array of characters after first letter and then Array.prototype.join('') to make it a string again. Omit the lowerRest parameter to keep the rest of the string intact, or set it to true to convert to lowercase.

将字符串的第一个字母大写。

使用数组解构和 String.prototype.toUpperCase() 把第一个字母大写,...rest 获取第一个字母后的字符组成的数组,然后 array .prototype.join(") 将其再次变为字符串。 省略 lowerRest 参数保持字符串的其余部分不变,或将其设置为 true 将字符串的剩余部分都转换为小写。

const capitalize = ([first, ...rest], lowerRest = false) =>
  first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'

capitalizeEveryWord

Capitalizes the first letter of every word in a string.

Use String.prototype.replace() to match the first character of each word and String.prototype.toUpperCase() to capitalize it.

将字符串中每个单词的第一个字母大写。

使用 String.prototype.replace() 匹配每个单词的第一个字符,并使用 String.prototype.toUpperCase() 将其大写。

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
capitalizeEveryWord('hello world!'); // 'Hello World!'

compactWhitespace

Returns a string with whitespaces compacted.

Use String.prototype.replace() with a regular expression to replace all occurrences of 2 or more whitespace characters with a single space.

返回替换空白字符后的字符串。

使用 String.prototype.replace() 将正则表达式匹配到的2个或更多空白字符替换为1个空白字符。

const compactWhitespace = str => str.replace(/\s{2,}/g, ' ');
compactWhitespace('Lorem    Ipsum'); // 'Lorem Ipsum'
compactWhitespace('Lorem \n Ipsum'); // 'Lorem Ipsum'

CSVToArray

Converts a comma-separated values (CSV) string to a 2D array.

Use Array.prototype.slice() and Array.prototype.indexOf('\n') to remove the first row (title row) if omitFirstRow is true. Use String.prototype.split('\n') to create a string for each row, then String.prototype.split(delimiter) to separate the values in each row. Omit the second argument, delimiter, to use a default delimiter of ,. Omit the third argument, omitFirstRow, to include the first row (title row) of the CSV string.

const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
  data
    .slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
    .split('\n')
    .map(v => v.split(delimiter));
CSVToArray('a,b\nc,d'); // [['a','b'],['c','d']];
CSVToArray('a;b\nc;d', ';'); // [['a','b'],['c','d']];
CSVToArray('col1,col2\na,b\nc,d', ',', true); // [['a','b'],['c','d']];

CSVToJSON

Converts a comma-separated values (CSV) string to a 2D array of objects. The first row of the string is used as the title row.

Use Array.prototype.slice() and Array.prototype.indexOf('\n') and String.prototype.split(delimiter) to separate the first row (title row) into values. Use String.prototype.split('\n') to create a string for each row, then Array.prototype.map() and String.prototype.split(delimiter) to separate the values in each row. Use Array.prototype.reduce() to create an object for each row's values, with the keys parsed from the title row. Omit the second argument, delimiter, to use a default delimiter of ,.

const CSVToJSON = (data, delimiter = ',') => {
  const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
  return data
    .slice(data.indexOf('\n') + 1)
    .split('\n')
    .map(v => {
      const values = v.split(delimiter);
      return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
    });
};
CSVToJSON('col1,col2\na,b\nc,d'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];
CSVToJSON('col1;col2\na;b\nc;d', ';'); // [{'col1': 'a', 'col2': 'b'}, {'col1': 'c', 'col2': 'd'}];

decapitalize

Decapitalizes the first letter of a string.

Use array destructuring and String.toLowerCase() to decapitalize first letter, ...rest to get array of characters after first letter and then Array.prototype.join('') to make it a string again. Omit the upperRest parameter to keep the rest of the string intact, or set it to true to convert to uppercase.

const decapitalize = ([first, ...rest], upperRest = false) =>
  first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar', true); // 'fOOBAR'

escapeHTML

Escapes a string for use in HTML.

Use String.prototype.replace() with a regexp that matches the characters that need to be escaped, using a callback function to replace each character instance with its associated escaped character using a dictionary (object).

const escapeHTML = str =>
  str.replace(
    /[&<>'"]/g,
    tag =>
      ({
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        "'": '&#39;',
        '"': '&quot;'
      }[tag] || tag)
  );
escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'

escapeRegExp

Escapes a string to use in a regular expression.

Use String.prototype.replace() to escape special characters.

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
escapeRegExp('(test)'); // \\(test\\)

fromCamelCase

Converts a string from camelcase.

Use String.prototype.replace() to remove underscores, hyphens, and spaces and convert words to camelcase. Omit the second argument to use a default separator of _.

const fromCamelCase = (str, separator = '_') =>
  str
    .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2')
    .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2')
    .toLowerCase();
fromCamelCase('someDatabaseFieldName', ' '); // 'some database field name'
fromCamelCase('someLabelThatNeedsToBeCamelized', '-'); // 'some-label-that-needs-to-be-camelized'
fromCamelCase('someJavascriptProperty', '_'); // 'some_javascript_property'

indentString

Indents each line in the provided string.

Use String.replace and a regular expression to add the character specified by indent count times at the start of each line. Omit the third parameter, indent, to use a default indentation character of ' '.

const indentString = (str, count, indent = ' ') => str.replace(/^/gm, indent.repeat(count));
indentString('Lorem\nIpsum', 2); // '  Lorem\n  Ipsum'
indentString('Lorem\nIpsum', 2, '_'); // '__Lorem\n__Ipsum'

isAbsoluteURL

Returns true if the given string is an absolute URL, false otherwise.

Use a regular expression to test if the string is an absolute URL.

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);
isAbsoluteURL('https://google.com'); // true
isAbsoluteURL('ftp://www.myserver.net'); // true
isAbsoluteURL('/foo/bar'); // false

isAnagram

Checks if a string is an anagram of another string (case-insensitive, ignores spaces, punctuation and special characters).

Use String.toLowerCase(), String.prototype.replace() with an appropriate regular expression to remove unnecessary characters, String.prototype.split(''), Array.prototype.sort() and Array.prototype.join('') on both strings to normalize them, then check if their normalized forms are equal.

const isAnagram = (str1, str2) => {
  const normalize = str =>
    str
      .toLowerCase()
      .replace(/[^a-z0-9]/gi, '')
      .split('')
      .sort()
      .join('');
  return normalize(str1) === normalize(str2);
};
isAnagram('iceman', 'cinema'); // true

isLowerCase

Checks if a string is lower case.

Convert the given string to lower case, using String.toLowerCase() and compare it to the original.

const isLowerCase = str => str === str.toLowerCase();
isLowerCase('abc'); // true
isLowerCase('a3@$'); // true
isLowerCase('Ab4'); // false

isUpperCase

Checks if a string is upper case.

Convert the given string to upper case, using String.prototype.toUpperCase() and compare it to the original.

const isUpperCase = str => str === str.toUpperCase();
isUpperCase('ABC'); // true
isLowerCase('A3@$'); // true
isLowerCase('aB4'); // false

mapString

Creates a new string with the results of calling a provided function on every character in the calling string.

Use String.prototype.split('') and Array.prototype.map() to call the provided function, fn, for each character in str. Use Array.prototype.join('') to recombine the array of characters into a string. The callback function, fn, takes three arguments (the current character, the index of the current character and the string mapString was called upon).

const mapString = (str, fn) =>
  str
    .split('')
    .map((c, i) => fn(c, i, str))
    .join('');
mapString('lorem ipsum', c => c.toUpperCase()); // 'LOREM IPSUM'

mask

Replaces all but the last num of characters with the specified mask character.

Use String.prototype.slice() to grab the portion of the characters that will remain unmasked and use String.padStart() to fill the beginning of the string with the mask character up to the original length. Omit the second argument, num, to keep a default of 4 characters unmasked. If num is negative, the unmasked characters will be at the start of the string. Omit the third argument, mask, to use a default character of '*' for the mask.

const mask = (cc, num = 4, mask = '*') => `${cc}`.slice(-num).padStart(`${cc}`.length, mask);
mask(1234567890); // '******7890'
mask(1234567890, 3); // '*******890'
mask(1234567890, -4, '$'); // '$$$$567890'

pad

Pads a string on both sides with the specified character, if it's shorter than the specified length.

Use String.padStart() and String.padEnd() to pad both sides of the given string. Omit the third argument, char, to use the whitespace character as the default padding character.

const pad = (str, length, char = ' ') =>
  str.padStart((str.length + length) / 2, char).padEnd(length, char);
pad('cat', 8); // '  cat   '
pad(String(42), 6, '0'); // '004200'
pad('foobar', 3); // 'foobar'

Recommended Resource - JavaScript: From Fundamentals to Functional JS

Learn higher-order functions, closures, scope, master key functional methods like map, reduce and filter and promises and ES6+ asynchronous JavaScript.

palindrome

Returns true if the given string is a palindrome, false otherwise.

Convert the string to String.prototype.toLowerCase() and use String.prototype.replace() to remove non-alphanumeric characters from it. Then, use the spread operator (...) to split the string into individual characters, Array.prototype.reverse(), String.prototype.join('') and compare it to the original, unreversed string, after converting it to String.prototype.toLowerCase().

const palindrome = str => {
  const s = str.toLowerCase().replace(/[\W_]/g, '');
  return s === [...s].reverse().join('');
};
palindrome('taco cat'); // true

pluralize

Returns the singular or plural form of the word based on the input number. If the first argument is an object, it will use a closure by returning a function that can auto-pluralize words that don't simply end in s if the supplied dictionary contains the word.

If num is either -1 or 1, return the singular form of the word. If num is any other number, return the plural form. Omit the third argument to use the default of the singular word + s, or supply a custom pluralized word when necessary. If the first argument is an object, utilize a closure by returning a function which can use the supplied dictionary to resolve the correct plural form of the word.

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);
};
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'

removeNonASCII

Removes non-printable ASCII characters.

Use a regular expression to remove non-printable ASCII characters.

const removeNonASCII = str => str.replace(/[^\x20-\x7E]/g, '');
removeNonASCII('äÄçÇéÉêlorem-ipsumöÖÐþúÚ'); // 'lorem-ipsum'

reverseString

Reverses a string.

Use the spread operator (...) and Array.prototype.reverse() to reverse the order of the characters in the string. Combine characters to get a string using String.prototype.join('').

const reverseString = str => [...str].reverse().join('');
reverseString('foobar'); // 'raboof'

sortCharactersInString

Alphabetically sorts the characters in a string.

Use the spread operator (...), Array.prototype.sort() and String.localeCompare() to sort the characters in str, recombine using String.prototype.join('').

const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');
sortCharactersInString('cabbage'); // 'aabbceg'

splitLines

Splits a multiline string into an array of lines.

Use String.prototype.split() and a regular expression to match line breaks and create an array.

const splitLines = str => str.split(/\r?\n/);
splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']

stringPermutations

⚠️ WARNING: This function's execution time increases exponentially with each character. Anything more than 8 to 10 characters will cause your browser to hang as it tries to solve all the different combinations.

Generates all permutations of a string (contains duplicates).

Use recursion. For each letter in the given string, create all the partial permutations for the rest of its letters. Use Array.prototype.map() to combine the letter with each partial permutation, then Array.prototype.reduce() to combine all permutations in one array. Base cases are for string length equal to 2 or 1.

const stringPermutations = str => {
  if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
  return str
    .split('')
    .reduce(
      (acc, letter, i) =>
        acc.concat(stringPermutations(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)),
      []
    );
};
stringPermutations('abc'); // ['abc','acb','bac','bca','cab','cba']

stripHTMLTags

Removes HTML/XML tags from string.

Use a regular expression to remove HTML/XML tags from a string.

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');
stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'

toCamelCase

Converts a string to camelcase.

Break the string into words and combine them capitalizing the first letter of each word, using a 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);
};
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'

toKebabCase

Converts a string to kebab case.

Break the string into words and combine them adding - as a separator, using a regexp.

const toKebabCase = str =>
  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('-');
toKebabCase('camelCase'); // 'camel-case'
toKebabCase('some text'); // 'some-text'
toKebabCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some-mixed-string-with-spaces-underscores-and-hyphens'
toKebabCase('AllThe-small Things'); // "all-the-small-things"
toKebabCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i-am-listening-to-fm-while-loading-different-url-on-my-browser-and-also-editing-xml-and-html"

toSnakeCase

Converts a string to snake case.

Break the string into words and combine them adding _ as a separator, using a regexp.

const toSnakeCase = str =>
  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('_');
toSnakeCase('camelCase'); // 'camel_case'
toSnakeCase('some text'); // 'some_text'
toSnakeCase('some-mixed_string With spaces_underscores-and-hyphens'); // 'some_mixed_string_with_spaces_underscores_and_hyphens'
toSnakeCase('AllThe-small Things'); // "all_the_smal_things"
toSnakeCase('IAmListeningToFMWhileLoadingDifferentURLOnMyBrowserAndAlsoEditingSomeXMLAndHTML'); // "i_am_listening_to_fm_while_loading_different_url_on_my_browser_and_also_editing_some_xml_and_html"

toTitleCase

Converts a string to title case.

Break the string into words, using a regexp, and combine them capitalizing the first letter of each word and adding a whitespace between them.

const toTitleCase = 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.charAt(0).toUpperCase() + x.slice(1))
    .join(' ');
toTitleCase('some_database_field_name'); // 'Some Database Field Name'
toTitleCase('Some label that needs to be title-cased'); // 'Some Label That Needs To Be Title Cased'
toTitleCase('some-package-name'); // 'Some Package Name'
toTitleCase('some-mixed_string with spaces_underscores-and-hyphens'); // 'Some Mixed String With Spaces Underscores And Hyphens'

truncateString

Truncates a string up to a specified length.

Determine if the string's length is greater than num. Return the string truncated to the desired length, with '...' appended to the end or the original string.

const truncateString = (str, num) =>
  str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str;
truncateString('boomerang', 7); // 'boom...'

unescapeHTML

Unescapes escaped HTML characters.

Use String.prototype.replace() with a regex that matches the characters that need to be unescaped, using a callback function to replace each escaped character instance with its associated unescaped character using a dictionary (object).

const unescapeHTML = str =>
  str.replace(
    /&amp;|&lt;|&gt;|&#39;|&quot;/g,
    tag =>
      ({
        '&amp;': '&',
        '&lt;': '<',
        '&gt;': '>',
        '&#39;': "'",
        '&quot;': '"'
      }[tag] || tag)
  );
unescapeHTML('&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'); // '<a href="#">Me & you</a>'

URLJoin

Joins all given URL segments together, then normalizes the resulting URL.

Use String.prototype.join('/') to combine URL segments, then a series of String.prototype.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter).

const URLJoin = (...args) =>
  args
    .join('/')
    .replace(/[\/]+/g, '/')
    .replace(/^(.+):\//, '$1://')
    .replace(/^file:/, 'file:/')
    .replace(/\/(\?|&|#[^!])/g, '$1')
    .replace(/\?/g, '&')
    .replace('&', '?');
URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo'); // 'http://www.google.com/a/b/cd?foo=123&bar=foo'

words

Converts a given string into an array of words.

Use String.prototype.split() with a supplied pattern (defaults to non-alpha as a regexp) to convert to an array of strings. Use Array.prototype.filter() to remove any empty strings. Omit the second argument to use the default regexp.

const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);
words('I love javaScript!!'); // ["I", "love", "javaScript"]
words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"]