A Comprehensive Guide to String Methods of JavaScript

A Comprehensive Guide to String Methods of JavaScript

25+ JavaScript String methods you should be aware of

In this article, I want to show you the commonly used String functions that every JavaScript developer should know. In addition to general examples, I have provided different use-case examples to clarify the context of functions.

Let's dive in and have fun!

Introduction

In JavaScript, a String is one of the primitive values and the String object is a wrapper around a String primitive. JavaScript’s strings are used for storing and manipulating text content. It can contain zero or more characters within quotes.

Following is a list of String object methods that every JavaScript developer should know:

String.charAt

The charAt method is used to find out a character value present at the specified index in a string. It takes an integer between 0 and str.length - 1 as a parameter and returns the specified index value as a string.

Note: As JavaScript starts counting from zero, the first index of a string is 0 and the last index would be str.length - 1.

let str = 'JavaScript';

console.log(str.charAt(0));
// Output: J

console.log(str.charAt(str.length - 1));
// Output: t

If the passed index is out of range, charAt returns an empty string.

console.log(str.charAt(123));
// Output: ""

Bonus Tip: There are two ways to access an individual character in a string. The first is the charAt method and the other way (introduced in ECMAScript 5) is to treat the string as an array-like object, where individual characters correspond to a numerical index. Let's take a look at the example below:

let str = 'JavaScript';

console.log(str[0]);
// Output: J

console.log(str[str.length - 1]);
// Output: t

console.log(str[123]);
// Output: undefined

If the passed index is out of range when using the array-like syntax while accessing string characters, undefined is returned.

console.log(str[123]);
// Output: undefined

String.charCodeAt

The charCodeAt method returns the Unicode of the specified index of a character in a string. This method takes a single parameter of an index, which should be an integer greater than or equal to 0 and less than the length of the string. If the index is not a number, it defaults to 0.

let str = 'JavaScript';

console.log(str.charCodeAt(0));
// Output: 74

String.concat

The concat method concatenates two or more strings together.

let noun = 'JavaScript';
let adjective = 'awesome';

console.log(noun.concat(' is ', adjective, '!'));
// Output: JavaScript is awesome!

Note: The concat method is a variadic function meaning it can take 1 to n parameters.

String.includes

The includes method performs a case-sensitive search to determine whether a string contains another string within it or not. This method returns true if the string contains the characters, and false if not.

let sentence = 'JavaScript is awesome!';
let word = 'awesome';

console.log(sentence.includes(word));
// Output: true

String.indexOf

According to the MDN Web Docs, indexOf method returns the position of the first occurrence of a specified value inside a string variable. If the specified value is not found, -1 is returned.

The method accepts two parameters:

  • The required parameter of searchValue indicates the content you want to search for in a string.
  • The optional start parameter indicates the position of the string in which the search will begin. If not specified, the search will start at the beginning.
let sentence = 'Keep betting on JavaScript!';
let searchTerm = 'betting';

console.log(sentence.indexOf(searchTerm, 0));
// Output: 5

console.log(sentence.indexOf(searchTerm, 7));
// Output: -1

Note: The indexOf method is case-sensitive.

String.localeCompare

The localeCompare method returns a number indicating whether a reference string comes before, or after, or is the same as the given string in sort order.

  • Negative when the referenceStr occurs before compareString
  • Positive when the referenceStr occurs after compareString
  • Returns 0 if they are equivalent

Let's look at this example from mdn:

// (1) The letter "a" is before "c" yielding a negative value
console.log('a'.localeCompare('c'));
// Output: -2 or -1 (or some other negative value)

// (2) The word "check" comes after "against" yielding a positive value
console.log('check'.localeCompare('against'));
// Output: 2 or 1 (or some other positive value)

// (3) "a" and "a" are equivalent yielding a neutral value of zero
console.log('a'.localeCompare('a'));
// Output: 0

Warning: Do not rely on exact return values of -1 or 1!

Negative and positive integer results vary between browsers (as well as between browser versions) because the W3C specification only mandates negative and positive values. Some browsers may return -2 or 2, or even some other negative or positive value.

Note: If you want to know more about how to sort array elements, luckily I've written a detailed guide plus a real case scenario on Sorting Array Elements. Check it out, you won't regret it.

String.match

The match method searches a string for a match against a regular expression, and returns the matches, as an Array object.

The match method is a powerful tool to use, but you need to know the basics of regular expressions.

Let's look at the example below from mdn to make it clear:

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);
// Output: Array ["T", "I"]

The above regex says to filter all uppercase characters from A to Z. And as you see the paragraph string has only two uppercase characters, and the expected output is an array of ["T", "I"].

String.matchAll

The matchAll method which is recently introduced is unlike the match method, it requires the global search flag and it will either return an iterator or an empty array.

Let's use the example of the match method and see the differences:

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

console.log(result);
// Output RegExpStringIterator

As you see the output, the result variable is a RegExpStringIterator. To see the iterator, you can either loop through or use the next method.

To convert the RegExpStringIterator object to an array, MDN advises using the spread operator.

const allMatches = [...result];

console.log(allMatches);
// Output: (2) [Array(1), Array(1)]

As you see the output, there is an array of arrays that wraps all the matches and their corresponding information.

String.normalize

The normalize method returns a string that contains the Unicode Normalization Form as specified by the form_type parameter.

Let's see the example below taken from mdn:

const name1 = '\u0041\u006d\u00e9\u006c\u0069\u0065';
const name2 = '\u0041\u006d\u0065\u0301\u006c\u0069\u0065';

console.log(`${name1}, ${name2}`);
// Output: "Amélie, Amélie"

console.log(name1 === name2);
// Output: false

console.log(name1.length === name2.length);
// Output: false

const name1NFC = name1.normalize('NFC');
const name2NFC = name2.normalize('NFC');

console.log(`${name1NFC}, ${name2NFC}`);
// Output: "Amélie, Amélie"

console.log(name1NFC === name2NFC);
// Output: true

console.log(name1NFC.length === name2NFC.length);
// Output: true

Characters are represented through a coding scheme like ASCII, UTF-8, etc., and some characters have more than one representation. So two strings may render similarly, but their Unicode may vary like name1 and name2 variables. So string comparison may fail here. We use the normalize method to return a single type of representation.

String.padStart

The padStart method is used to pad the start of a string with a specific string to a certain length. Let's take a look at the example below:

const str = 'JS';

console.log(str.padStart(6));
// Output:     JS

console.log(str.padStart(7, 'Hello'));
// Output: HelloJS

console.log(str.padStart(6, '0'));
// Output: 0000JS

console.log(str.padStart(1));
// Output: JS

Bonus Tip: The padStart method looks so simple but it does magic when it comes to its real-life use-cases. For example, displaying only a part of a credit card number and padding the remaining characters with *, displaying only two digits of phone number when passing a two-factor authentication, and many other cases.

Let's have a look at the example below:

let dollars = 10;
let cents = 3;

console.log('$' + dollars + '.' + cents.toString().padStart(2,0));
// Output: $10.03

String.padEnd

The padEnd method is used to pad the end of a string with a specific string to a certain length. It takes two parameters of targetLength and padString.

Take a look at the example below:

const str = 'JavaScript';

console.log(str.padEnd(15, 't'));
// Output: JavaScriptttttt

console.log(str.padEnd((str.length) + 3, '.')); 
// Output: JavaScript...

String.raw

The raw method is the tag function of template literals.

let num1 = 4;
let num2 = 3;

let result = String.raw`${num1} + ${num2} = ${num1 + num2}`;

console.log(result);
// Output: 4 + 3 = 7

String.repeat

The repeat method takes a number as an argument and repeats the string as many times as specified and returns as a single string.

const lang = 'JavaScript';

let repeatedString = lang.repeat(3);

console.log(repeatedString);
// Output: JavaScriptJavaScriptJavaScript

String.replace

The replace method searches a string for a specified value, or a regular expression, and returns a new string where the specified values are replaced. w3schools.com

const str = 'Mr Blue has a blue house and a blue car.';

let newString = str.replace(/blue/g, 'red');

console.log(newString);
// Output: Mr. Blue has a red house and a red car.

In the example above, all the occurrences are replaced because a /g flag is added to the regular expression. Let's see the example below without using a regular expression:

const str = 'Mr. Blue has a blue house and a blue car.';

let newString = str.replace('blue', 'red');

console.log(newString);
// Output: Mr. Blue has a red house and a blue car.

As you can see, just the first occurrence of the word blue is replaced when not using a regular expression that has a /g flag which means global.

String.replaceAll

The replaceAll method is a new feature that is added in ES2021/ES12. This method searches and replaces all string occurrences with the defined pattern which can be a string or a regular expression. Let's take a look at the example below:

const str = 'Mr. Blue has a blue house and a blue car.';

let newString = str.replaceAll('blue', 'red');

console.log(newString);
// Output: Mr. Blue has a red house and a red car.

Bonus Tip: Let's do some fancy thing using the replace method:

const str = "Mr Blue has a blue house and a blue car";
str.replace(/blue|house|car/gi, (x) => {
  return x.toUpperCase();
});

// Output: Mr BLUE has a BLUE HOUSE and a BLUE CAR

The regular expression, performs a global and case-insensitive replacement.

Note: The credit of the example goes to w3schools.com!

String.search

The search method searches a string for a specified value and returns the position of the match.

  • The search value can be a string or a regular expression.
  • The method returns -1 in case no match is found.

Take a look at the example:

const str =  'Hello, JavaScript!';

let pos = str.search('JavaScript');

console.log(pos);
// Output: 7

String.slice

The slice method extracts a portion of a string and returns it as a new string, without modifying the original string.

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

console.log(str.slice(31));
// Output: "the lazy dog."

console.log(str.slice(4, 19));
// Output: "quick brown fox"

console.log(str.slice(-4));
// Output: "dog."

console.log(str.slice(-9, -5));
// Output: "lazy"

Note: The credit of the example above goes to mdn!

Bonus Tip: Let's do something fancy. I'll use both search and slice methods to extract a specific word.

const str = 'What is JavaScript?';
const word = 'JavaScript';

let position = str.search(word);
let slicedString = str.slice(position, position + word.length);

console.log(slicedString)
// Output: JavaScript

String.split

The split method divides a String into an ordered list of substrings, puts these substrings into an array, and returns the array.

  • The split method takes a separator param which divides a string into an array of substrings according to it.
  • If an empty string is used as the separator, an array of characters is returned.
  • The split method does not change the original array.
const str = 'Hassib loves writing JavaScript';
const space = ' ';

let words = str.split(space);

console.log(words);
// Output: (4) ['Hassib', 'loves', 'writing', 'JavaScript']

Bonus Tip: Let's do something fancy using the split method ;-)

const email = 'hassib.moddasser@gmail.com';

let subStrings = email.split('@');

console.log('Name: ' + subStrings[0]);
console.log('Domain: ' + subStrings[1]);

// Name: hassib.moddasser
// Domain: gmail.com

String.startsWith

The startsWith method checks if a string begins with the string you passed as a parameter.

const str = 'Hello, World!';

console.log(str.startsWith('Hello'));
// Output: true

String.endsWith

The endsWith method checks if a string ends with the string you passed as a parameter.

const str = 'Hassib is writing JavaScript';

console.log(str.endsWith('PHP'));
// Output: false

console.log(str.endsWith('JavaScript'));
// Output: true

String.toLowerCase

The toLowerCase method converts a string to lowercase letters.

const str = 'Hello, World!';

console.log(str.toLowerCase());
// Output: hello, world!

String.toUpperCase

The toLowerCase method converts a string to uppercase letters.

const str = 'Hello, World!';

console.log(str.toUpperCase());
// Output: HELLO, WORLD!

String.toLocaleLowerCase

The toLocaleLowerCase method returns the calling string value converted to lower case, according to any locale-specific case mappings. mdn

Let's look at the coding snippet below to find out how it works:

const dotted = 'İstanbul';

console.log(dotted.toLocaleLowerCase('en-US'));
// Output: "i̇stanbul"

console.log(dotted.toLocaleLowerCase('tr'));
// Output: "istanbul"

String.toLocaleUpperCase

The toLocaleUpperCase method returns the calling string value converted to upper case, according to any locale-specific case mappings. mdn

const city = 'istanbul';

console.log(city.toLocaleUpperCase('en-US'));
// Output: "ISTANBUL"

console.log(city.toLocaleUpperCase('TR'));
// Output: "İSTANBUL"

String.trimStart

The trimStart method removes whitespace from the beginning of a string.

const str = '    I used to code in JavaScript         ';

console.log(str.trimStart());
// Output: "I used to code in JavaScript         "

String.trimEnd

The trimEnd method removes whitespace from the end of a string.

const str = '    I used to code in JavaScript         ';

console.log(str.trimEnd());
// Output: "    I used to code in JavaScript"

String.trim

The trim method removes spaces from both ends of a string.

const str = '    I used to code in JavaScript         ';

console.log(str);
// Output: "    I used to code in JavaScript         "

console.log(str.trim());
// Output: "I used to code in JavaScript"

Note: Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.). mdn

String.toString

The toString method returns a string representing the specified object.

let str = new String('Hello, JS');

console.log(str);
// Output: String {'Hello, JS'}

console.log(str.toString());
// Output: 'Hello, JS'

Note: When you initialize a string variable using the String object, it's treated as an Object anymore.

Summary

The String object is used to represent and manipulate a sequence of characters. It has just one property, 3 static methods, and more than 30 Instance methods.

Let's look at a glance at the most useful String methods that we've discussed above:

FunctionDescription
chartAt(index)Returns the specified index character from a string.
charCodeAt(index)Returns the Unicode of the specified index of a character in a string.
concat(str [, ...strN])Concatenates two or more strings together.
indexOf(searchValue)Returns the position of the first occurrence of a specified value inside a string variable.
localeCompare(str)Returns a number indicating whether a reference string comes before, or after, or is the same as given string in sort order.
match(regexp)Searches a string against for a match against a regular expression, and returns the matches as an array object.
matchAll(regexp)Requires a global flag and returns an iterator of matches or an empty array.
normalize([form])Returns a string that contains a Unicode Normalization Form.
padStart(targetLength)Pads the start of the string with a specific string.
padEnd(targetLength)Pads the end of the string with a specific string.
String.rawIs the tag function of Template Literal.
repeat(count)Repeats a string as many times specified.
replace(searchFor, replaceWith)Searches a string for a specified value or a Regular Expression, and returns the new string where specified values are replaced.
replaceAll(searchFor, replaceWith)Searches and replaces all string occurrences.
search(regexp)Searches a string for a specified value.
slice(beginIndex [, endIndex])Extracts a portion of string and returns it as a new string.
split([sep [, limit] ])Divides a string into and ordered list of substrings and return them as an array.
startsWith(searchStr [, length])Checks if a string begins with the string you passed.
endsWith(searchStr, [, length])Check if a string ends with the string you passed.
toLowerCase()Converts a string to lowercase letters.
toUpperCase()Converts a string to uppercase letter.
toLocaleLowerCase([locale, ...n]Converts a string to lowercase letters according to any locale-case specific mappings.
toLocaleUpperCase([locale, ...n])Converts a string to uppercase letters according to any locale-case specific mappings.
trimStart()Removes whitespace from the beginning of a string.
trimEnd()Removes whitespace from the end of a string.
trim()Removes whitespace from both ends of a string.
toString()Returns a string representing the specified object.

Before you leave

If you would love to read even more content like this, feel free to visit me on Twitter and LinkedIn.

I'd love to count you as my ever-growing group of awesome friends!