JavaScript String Methods Cheat Sheet


How is this JavaScript String Methods cheat sheet helpful to you? We all use strings in our code in one form or the other. Usually, primitive values like "Hello, world!" cannot have properties or methods on them as they're not objects. But with JavaScript, methods and properties are also available to primitive values, and this is because JavaScript treats primitive values as objects when executing methods and properties.

The String is an object that is used to represent and manipulate a sequence of characters.

Or, in other words, it's zero or more characters written inside quotes. It stores textual data, and there is no particular type for a single character. Usually, the internal format for strings is always UTF-16, but it's not tied to the page encoding.

Note that in the context of string primitives and objects, while they may share many behaviors, they do have other significant differences. String literals and strings returned from String calls are primitive strings. In contrast, in contexts where a method is invoked on a primitive string, JavaScript automatically wraps the string primitive and calls the method.

Here are a few examples where we can see strings are being used:

const string1 = "Hello, world!";
const string2 = 'My name is John Doe';
const string3 = `I am a string :)`;

Also, we can use String as:

const string4 = new String("Hello, string!");

Or use it with values like:

const name = 'Peter';
const name1 = "Jack";
const result = `The names are ${name} and ${name1}`;

However, we cannot have such a string as it will cause an error:

const name = 'My name is 'Peter';

Strings are useful for holding data so that it can be represented in text form. We generally use them to check their length, build and concatenate them, and more.

But what methods are available to us in JavaScript? Let's try to answer all in this cheat sheet.


Basic level - JavaScript String Methods Cheat Sheet

1. Different ways to create a string

As you might have seen in the above code example, there are a few ways in which you can create a string in JavaScript. They can be created as primitives, from string literals, or as objects using the String() constructor. Let's take a look at an example for both of these:

String primitive

const stringPrimitive = "I am a string made from a primitive";

The second way to create a string primitive is to use single quotes:

const stringPrimitiveSingleQuotes = "I am also a string made from a primitive but with single quotes";

And finally, they can also be created using the backtick character (`). This form typically specifies a template literal or template strings where you can interpolate expressions by injecting embedded expressions. But here we will share a simple template string example:

const templateString = `I am a string primitive that's using a backtick character for template strings!`;

String object

const stringObject = new String("I am a String object");

2. Instance methods: at()

The at() method takes in an integer value and returns a new String consisting of a single UTF-16 code unit located at the specified integer offset or index.

It allows both positive and negative integers, but negative integers count back from the last string character.

Syntax:

at(index)

The index parameter is the position of the string character to be returned. The at method returns undefined if the given index can’t be found.

Examples:

  1. Returning the last character of a string:
function returnLastChar(arr) {
  return arr.at(-1);
}

let invoiceRef = 'myinvoice01';

console.log(returnLast(invoiceRef));
// Logs: '1'

invoiceRef = 'myinvoice02';

console.log(returnLast(invoiceRef));
// Logs: '2'

2. Comparing methods:

const myString = 'Hello, how you doing?';

const compare = myString.at(-8);
console.log(compare); // Logs: 'u'

3. toLowerCase()

The toLowerCase() method returns the calling string value converted to lowercase.

It doesn't affect the value of the string itself.

Syntax:

toLowerCase()

A new converted lowercase string is returned when toLowerCase() is called.

const sentence = 'YOU have a new Notification!';

console.log(sentence.toLowerCase()); // Logs: "you have a new notification!"

We can also call it directly inside console.log as:

console.log('ABCD'.toLowerCase()); // 'abcd'

4. concat()

The concat() method concatenates the string arguments to the calling string to return a new string.

Changes to the original or returned string don't affect the other. If, for example, the arguments are not of type string, they are converted to string values before concatenating.

Note: Don't confuse it with the addition or string concatenation operators like +, += etc. The difference is that the concat() method coerces its arguments directly to strings while addition coerces its operands to primitives first.

Syntax:

concat(str1)
concat(str1, str2)
concat(str1, str2, /* …, */ strN)

Here, strN is one or more strings concatenated to str.

Examples:

const greeting = 'Hello, ';
console.log(hello.concat('World!', '. Let's study JavaScript.'));
// Hello, World. Let's study JavaScript.

We can use it with arrays like:

const greetList = ['Hello', ' ', 'John', '!'];
"".concat(...greetList) // "Hello John!"

5. indexOf()

The indexOf() method searches the entire calling string and returns the index of the first occurrence of the specified substring.

There should be one given argument that can be a substring to search for. Given a second argument, let's say a number, the method returns the first occurrence at an index greater than or equal to the specified number.

Syntax:

indexOf(searchString)
indexOf(searchString, position)

The searchString is the substring to search for coerced to a string. If indexOf() is called with no arguments, searchString is coerced to "undefined". Here, position is optional. The method returns the index of the first occurrence greater than or equal to position, which by default is 0.

Examples:

const str = 'I love JavaScript!';

console.log(`Index of first w from start is ${str.indexOf('o')}`); // 3
console.log(`Index of "new" from start is ${str.indexOf('JavaScript')}`); // 7

The second position argument can be used as:

'hello world'.indexOf('', 3) // 3
'hello world'.indexOf('', 22) // 11

The method is also case sensitive; for example:

console.log('Apple pie'.indexOf('apple')); // -1

We can use it with a template string as:

const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';

const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);

console.log(`The index of the first "${searchTerm}" from the beginning is ${indexOfFirst}`);
// expected output: "The index of the first "dog" from the beginning is 40"

console.log(`The index of the 2nd "${searchTerm}" is ${paragraph.indexOf(searchTerm, (indexOfFirst + 1))}`);
// expected output: "The index of the 2nd "dog" is 52"

Intermediate Level - JavaScript String Methods Cheat Sheet

1. includes()

The includes() method performs a case-sensitive search to determine whether one string may be found within another string.

Syntax:

includes(searchString)
includes(searchString, position)

Here searchString is the string to be searched for within str , and the optional position is the position at which to begin searching. The return value is true if the search string is found anywhere within the given string; otherwise false.

Examples:

const sentence = 'The quick brown fox jumps over the lazy dog.';

const word = 'the';

console.log(`The word "${word}" ${sentence.includes(word) ? 'is' : 'is not'} in the sentence`);
// expected output: "The word "the" is in the sentence"

To check case sensitivity, let's use the following example:

console.log('Apple pie'.includes('apple')); // false

2. endsWith()

The endsWith() method determines whether a string ends with the characters of a specified string.

Syntax:

endsWith(searchString)
endsWith(searchString, endPosition)

Here searchString are the characters to be searched for at the end of str. The optional endPosition parameter is the end position at which searchString is expected to be found, and it defaults to str.length.

This method returns true if the given characters are found at the end of the string, else false. It's case-sensitive.

Examples:

const str = 'he quick brown fox jumps over the lazy dog.';

console.log(str.endsWith('dog.')); // true
console.log(str.endsWith('over the')); // false
console.log(str.endsWith('quick', 19)); // false

3. localeCompare()

The localeCompare() method returns a number that indicates whether a string comes before, or after, or is the same as the given string in sort order.

Note: When you implement localeCompare() with Intl.Collator API, this method will call the relevant Intl.Collator.

Syntax:

localeCompare(compareString)
localeCompare(compareString, locales)
localeCompare(compareString, locales, options)

The locales and options are the optional parameters that customize the behavior of the function and let the apps specify the language conventions to be used. The compareString is the string against which the referenceStr is compared.

It returns a negative number if referenceStr occurs before compareString, a positive if it occurs after compareString, and 0 if they are equivalent.

Examples:

const a = 'réservé';
const b = 'RESERVE';

console.log(a.localeCompare(b)); // 1
console.log(a.localeCompare(b, 'en', { sensitivity: 'base' })); // 0

This can also be used to sort an array:

var a = 'Ferrari';
var b = 'Mercedes';

if (a.localeCompare(b) < 0) 
  console.log('"Ferrari" comes before "Mercedes"');
 else if (a.localeCompare(b) > 0) 
  console.log('"Ferrari" comes after "Mercedes"');
 else if (a.localeCompare(b) == 0) 
  console.log('Both strings equal');

// "Ferrari" comes before "Mercedes"

Plus, we can also do number sorting:

console.log("2".localeCompare("10")); // 1

console.log("2".localeCompare("10", undefined, { numeric: true })); // -1

console.log("2".localeCompare("10", "en-u-kn-true")); // -1

4. match()

The match() method retrieves the result of matching a string against a regular expression (regexp).

Syntax:

match(regexp)

Here regexp is a regular expression object or any object having the Symbol.match method. If it's not any of these, it's implicitly converted to a regexp by using new RegEx(regexp).

It returns an array whose contents depend on the presence or absence of the global (g) flag of the regexp or null if there are no matches.

Examples:

const paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
const regex = /[A-Z]/g;
const found = paragraph.match(regex);

console.log(found); // Array ["T", "I"]

We can also use match() without any parameters:

const str = "Hello there, how's your pet?";

console.log(str.match()); // Array [""]

5. repeat()

The repeat() method constructs and returns a new string that contains the specified number of copies of the string on which it was called.

This new string is concatenated together.

Syntax:

repeat(count)

The count is an integer between 0 and +Infinity and indicates the number of times to repeat the string.

Examples:

const ourMotto = 'We want justice! \n';

console.log(ourMotto.repeat(5));
// "We want justice! 
// We want justice! 
// We want justice! 
// We want justice! 
// We want justice!

Here are some other examples:

'abc'.repeat(3.5) // 'abcabcabc'
`abc'.repeat(1) // 'abc'
'abc'.repeat(2) // 'abcabc'

6. replace()

The replace() method returns a new string with one, some, or all matches of a pattern that will be replaced by a replacement.

The pattern can be a string or a RegExp, and the replacement can be a string or a function called for each match.

Syntax:

replace(pattern, replacement)

Note: If pattern is a string, only the first occurrence will be replaced, and the original string is left unchanged. Any value that doesn't have the Symbol.replace method will be coerced to a string. Also, this method doesn't mutate the string it's called on and instead returns a new string.

Here, replacement can be a string or a function:

  • If it's a string, it will replace the substring matched by the pattern. The replacement string can include special patterns like $$, $&, $', $n etc.
  • If it's a function, it will be invoked for every match, and its return value is used as the replacement text. This function will have the following signature:
function replacer(match, p1, p2, /* …, */ pN, offset, string, groups) {
  return replacement;
}

Examples:

let text = "Visit our office again!";
let result = text.replace("office", "home");

console.log(result); // 'Visit our home again!'

Here's an example that uses regexp:


const str = 'Twas the night before Xmas...';
const newstr = str.replace(/xmas/i, 'Christmas');

console.log(newstr); // 'Twas the night before Christmas...'

It can be used to switch words in a string. In the following example, we will switch the name:

const re = /(\w+)\s(\w+)/;
const str = 'John Doe';
const newstr = str.replace(re, '$2, $1');

console.log(newstr); // 'Doe, John'

7. slice()

The slice() method extracts a section of a string and returns it as a new string without modifying the original string.

Syntax:

slice(indexStart)
slice(indexStart, indexEnd)

Here indexStart is the index of the first character to include in the returned substring, and indexEnd is the optional index of the first character to exclude from the returned substring.

Note: This method extracts up to (but not including) indexEnd. For example, str.slice(3, 9) extracts the fourth character through the ninth character.

Examples:

We can create a new string as:

const str1 = 'Rise and shine and keep smiling.'
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -2),
str4 = str1.slice(12),
str5 = str1.slice(30);

console.log(str2); // 'ise and'
console.log(str3); // ' and shine and keep smilin'
console.log(str4); // 'ne and keep smiling.'
console.log(str5); // 'g. '

We can also provide negative indexes:

const str = 'The morning is upon us.';

str.slice(-3); // returns 'us.'
str.slice(-3, -1); // returns 'us'
str.slice(0, -1); // returns 'The morning is upon us'
str.slice(4, -1); // returns 'morning is upon us'

8. split()

The split() method takes a pattern and divides a String into an ordered list of substrings by searching for the pattern, puts these substrings into an array, and then returns it.

Syntax:

split()
split(separator)
split(separator, limit)

Both the separator and limit parameters are optional. separator is the pattern describing where each split should occur. The original string is returned wrapped in an array if it's undefined. The second limit parameter is a non-negative integer specifying a limit on the number of substrings to be included in the array.

If separator is a non-empty string, the target string is split by all matches of the separator without including the separator in the results. While if it's an empty string, the str is converted to an array of its UTF-16 characters.

Examples:

const emptyString = ' ';

console.log(emptyString.split()); // [""]
console.log(emptyString.split(emptyString)); // []

Here's an example with a sentence:


const str = 'The quick brown fox jumps over the lazy dog.';

const words = str.split(' ');
console.log(words[4]); // "jumps"

const chars = str.split('');
console.log(chars[5]); // "u"

const strCopy = str.split();
console.log(strCopy); // Array ["The quick brown fox jumps over the lazy dog."]

We can also return a limited number of splits:

const myString = 'How are you doing?'
const splits = myString.split(' ', 2)

console.log(splits) // Array ["How", "are"]

9. toString()

The toString() method of a string object returns a string representing the specified string.

The String object overrides the toString() method of the Object. It returns the String wrapper object.

Syntax:

toString() 

Examples:

const x = new String("Hello world");

console.log(x.toString()); // 'Hello world'

const stringObj = new String('John');

console.log(stringObj); // String { "John" }
console.log(stringObj.toString()); // "John"

10. valueOf()

The valueOf() method returns the primitive value of a String object.

It returns it as a string data type whose value is equivalent to String.prototype.toString(). This method is called internally by JavaScript and not explicitly in code.

Syntax:

valueOf()

Examples:

const x = new String('Hello world');
console.log(x.valueOf()); // 'Hello world'
const stringObj = new String('hello');

console.log(stringObj); // String { "hello" }
console.log(stringObj.valueOf()); // "hello"

Advanced Level - JavaScript String Methods Cheat Sheet

1. Static methods: fromCharCode()

The static String.fromCharCode() method returns a string created from the specified sequence of UTF-16 code units.

It returns a single string and not a String object. As it's a static method, therefore we can use it as String.fromCharCode() rather than as a method.

Syntax:

String.fromCharCode(num1)
String.fromCharCode(num1, num2)
String.fromCharCode(num1, num2, /* …, */ numN)

Here, num1, ..., numN is a sequence of numbers that are UTF-16 code units. No validity checks are performed here, and it returns a string of length N consisting of the N specified UTF-16 code units.

Examples:

String.fromCharCode(65, 66, 67); // "ABC"
String.fromCharCode(0x2014); // "—"
String.fromCharCode(0x12014); // "—"
String.fromCharCode(8212); // "—"

The supplementary characters in UTF-16 require two code units, as shown below:


String.fromCharCode(0xD83C, 0xDF03); // Code Point U+1F303 "Night with
String.fromCharCode(55356, 57091); // Stars" === "\uD83C\uDF03"
String.fromCharCode(0xD834, 0xDF06, 0x61, 0xD834, 0xDF07); // "\uD834\uDF06a\uD834\uDF07"

2. raw()

The static String.raw() method is a tag function of template literals. It's used to get the raw string form of template literals.

This means that substitutions like ${foo} are processed, but escape sequences like \n are not processed. The raw() method has close semantics to an untagged literal since it concatenates all arguments and returns a string.

Syntax:

String.raw(strings, ...substitutions)
String.raw`templateString`

Here strings are well-formed template literal array object like { raw: ['foo', 'bar', 'baz'] }, and it should be an object whose value is an array-like object of strings. The second parameter, substitutions, contains substitution values, while the templateString is a template literal that comes optionally with substitutions.

This method returns a raw string form of a given template literal. If it's called with an object whose raw property doesn't have a length property or a non-positive length, it returns an empty string " ". While if substitutions.length is less than strings.raw.length - 1, then the rest of the placeholders are filled with empty strings.

Examples:

const filePath = String.raw`C:\Web Projects\ReactJS\readme.md`;

console.log(`The file was uploaded from: ${filePath}`); // "The file was uploaded from: C:\Web Projects\ReactJS\readme.md"

We can also build an identity tag with it, although it's not recommended to use raw() directly just to build an identity tag.

const html = (strings, ...values) => String.raw({ raw: strings }, ...values);

const doc = html`<canvas>\n</canvas>`;
// "<canvas>\n</canvas>"

3. codePointAt()

The codePointAt() method returns a non-negative integer that is the Unicode code point value at the given position.

Note: This function doesn't give the nth code point in a string; instead, it provides the code point starting at the specified string index.

Syntax:

codePointAt(pos)

Here pos is the position of an element in the str to return the code point value from. This method returns a decimal number that represents the code point value:

  • If there's no element at pos, it returns undefined.
  • If the element at pos is a UTF-16 high surrogate, it returns the code point of the surrogate pair.
  • If the element at pos is a UTF-16 low surrogate, it returns only the low surrogate code point.

Examples:

A typical example can be to get the code of an emoji value:

const emoji = '😄';

console.log(emoji.codePointAt(1)); // 56836

Other examples include characters and UTF-16 values:


'ABC'.codePointAt(0); // 65
'\ud83d\ude0d'.codePointAt(0); // 128525
'ABC'.codePointAt(42); // undefined

We can also loop with codePointAt() because indexing to a pos whose element is a UTF-16 low surrogate returns only the low surrogate. For this, we can use a for...of statement as:

for (const codePoint of '\ud83d\udc0e\ud83d\udc71\u2764') {
  console.log(codePoint.codePointAt(0).toString(16))
}
// '1f40e', '1f471', '2764'

4. search()

The search() method executes a search for a match between a regexp and a String object.

It calls the Symbol.search method of the argument with the string as the first parameter.


Note: The g flex of regexp does not affect the search() result. The search always happens as if the regex's lastIndex is 0.

Syntax:

search(regexp)

Here regexp is a regular expression object or any object having a Symbol.search method. If it's not this, then it's implicitly converted to a RegExp by using new RegExp(regexp). It returns the index of the first match between the regexp and the given string. If nothing is found, it returns -1.

Examples:

const paragraph = 'The quick brown fox jumps over the lazy dog.';
const regex = /[^\w\s]/g;

console.log(paragraph.search(regex)); // 43
console.log(paragraph[paragraph.search(regex)]); // "."

We can also search a string with two different regexp objects to show a successful search:

const str = "john DoE";
const re = /[A-Z]/;
const reDot = /[.]/;

console.log(str.search(re)); // 5
console.log(str.search(reDot)); // -1

5. fromCodePoint()

The static fromCodePoint() method returns a string created using the specified code point sequences.

As it's a static method of String, we must call it as String.fromCodePoint() instead of a method of a String object you created.

Syntax:

String.fromCodePoint(num1)
String.fromCodePoint(num1, num2)
String.fromCodePoint(num1, num2, /* …, */ numN)

Here the num1, ..., numN is a sequence of code points.

Examples:

String.fromCodePoint(42); // "*"
String.fromCodePoint(65, 90); // "AZ"
String.fromCodePoint(0x404); // "\u0404" === "Є"

console.log(String.fromCodePoint(9731, 9733, 9842, 0x2F804)); // "☃★♲你"

The following will cause a RangeError as we are providing a negative input:

String.fromCodePoint('_'); // RangeError
String.fromCodePoint(Infinity); // RangeError
String.fromCodePoint(-1); // RangeError
String.fromCodePoint(3.14); // RangeError

Conclusion - JavaScript String Methods Cheat Sheet

In this JavaScript String methods cheat sheet, we covered what is a string in JavaScript, why it is used, and how to declare a string in multiple ways. Then, we explained all the essential string methods and relevant examples from beginner to advanced levels.
We hope this cheat sheet will help you utilize the important string methods in your next project.