githubEdit

String methods cheatsheet

Download image versionarrow-up-right

Changing the case

  • toLowerCase / toUpperCase()\

const str = "Hello";
const low = str.toLowerCase(); // hello
const up = str.toUpperCase(); // HELLO

Combining strings

  • concat(...items) Combines two or more strings and returns one string

const str = "Hello";
const str2 = "World!";
const newStr = str.concat(" ", str2);
// newStr = "Hello World!"

Splitting a string

  • split(separator, limit) Splits a string into an array by the specified separator, which can be a substring or a regular expression


Repeating a string

  • repeat(count) Repeats the string the specified number of times


  • charAt(index) Returns a character at the specified index

  • includes(substr, startPositon) Checks if the string contains the specified substring and returns true/false

  • indexOf / lastIndexOf(substr, startPositon) Returns the index of the first/last substring found, otherwise returns -1

  • endsWith / startsWith(substr, searchLength) Checks if the string ends/starts with the specified substring and returns true/false

  • search(substr) Checks if there is a specified substring or regular expression in the string and returns the index of the beginning of the match


Extracting a substring

  • slice(start, end) Extracts part of the string starting at the start position and ending at the end-1 position

  • substring(start, end) Extracts substring from a string between start and end. Unlike slice(), you can set start more than end.

  • substr(start, length) Extracts part of a string of a specified length. The first parameter can be negative, then the position is determined from the end of the string.


Replacing a substring

  • replace(substr, newSubstr) Searches for the specified substring (or regular expression) in the string and replaces it with another one

  • replaceAll(substr, newSubstr) Replaces all found matches with another string or passed function


Adding characters

  • padStart / padEnd(strLength, str) Adds padding at the beginning/end of a string until the string reaches the length specified by the first parameter


Removing spaces

  • trim / trimStart / trimEnd() Deletr spaces at both ends of the string, either only at the beginning or only at the end


Working with ASCII code

  • charCodeAt(index) Returns the ASCII code of the character at the specified index

  • fromCharCode(...code) Converts ASCII code to readable characters

Last updated