Skip to content

Working with Strings in JavaScript

Posted on:November 9, 2023 at 09:03 AM

Strings are one of the most common data types in JavaScript. And luckily, JavaScript has some very useful built-in string methods for manipulating and working with text. In this post, I’ll share some of my favorite JavaScript string methods with code examples.

Accessing Individual Characters

You can access individual characters in a string as if it were an array:

const airline = "TAP Air Portugal";

console.log(airline[0]); // T
console.log(airline[7]); // A

The .length property also works on strings:

console.log(airline.length); // 17

Finding the Index of Substrings

Methods like .indexOf() and .lastIndexOf() allow you to find the index of a substring inside a string:

const airline = "TAP Air Portugal";

console.log(airline.indexOf("r")); // 6
console.log(airline.lastIndexOf("r")); // 10
console.log(airline.indexOf("Portugal")); // 8

Extracting Substrings

The .slice() method extracts a part of a string and returns a new string:

const airline = "TAP Air Portugal";

console.log(airline.slice(4, 7)); // 'Air'
console.log(airline.slice(4)); // 'Air Portugal'

You can even use negative indexes to slice from the end:

console.log(airline.slice(-2)); // 'al'

Extracting Parts of a String

We can get the first or last part of a string using .slice():

// get the first word
console.log(airline.slice(0, airline.indexOf(" ")));
// get the last word
console.log(airline.slice(airline.lastIndexOf(" ") + 1));

Changing Case

.toLowerCase() and .toUpperCase() change the case of a string:

const airline = "TAP Air Portugal";

console.log(airline.toLowerCase()); // 'tap air portugal'
console.log(airline.toUpperCase()); // 'TAP AIR PORTUGAL'

You can use these methods together with .slice() to capitalize names:

const passenger = "joe";
const passengerCorrected =
  passenger[0].toUpperCase() + passenger.slice(1).toLowerCase();

console.log(passengerCorrected); // 'Joe'

Replacing Substrings

.replace() replaces only the first match by default:

const announcement = "All passengers come to boarding door 23.";

announcement.replace("door", "gate"); // 'All passengers come to boarding gate 23.'

To replace all occurrences, use a regular expression with the global flag /g:

announcement.replace(/door/g, "gate"); // 'All passengers come to boarding gate 23.'

Trimming Whitespace

.trim() removes whitespace from both ends:

const email = "     hello@joe.io      \n";

console.log(email.trim()); // 'hello@joe.io'

Splitting and Joining

.split() divides a string into an array based on a separator. .join() does the reverse - it creates a string from an array by joining all elements together.

const name = "Harry Potter";

const nameArray = name.split(" "); // ['Harry', 'Potter']

const nameString = nameArray.join("-"); // 'Harry-Potter'

Converting to an Array

.split() divides a string into an array by a separator. This is useful for convert comma-separated strings to arrays:

const genres = "Action,Drama,Romance";

genres.split(","); // ['Action', 'Drama', 'Romance']

Padding Strings

.padStart() and .padEnd() allow you to pad a string to a certain length by adding characters at the start or end:

"12".padStart(10, "0"); // '0000000012'
"12".padEnd(10, "x"); // '12xxxxxxxx'

This can be useful for formatting numbers or IDs.

const maskCreditCard = function (number) {
  const str = number + "";
  const last = str.slice(-4);
  return last.padStart(str.length, "*");
};

console.log(maskCreditCard(64637836)); // ******7836
console.log(maskCreditCard(43378463864647384)); // ************7384
console.log(maskCreditCard("334859493847755774747")); // *****************4747

Repeating Strings

.repeat() repeats a string a specified number of times:

"Na".repeat(10); // 'NaNaNaNaNaNaNaNaNaNa'

This can be handy for creating separators or placeholders.

That’s just a quick overview of some useful JavaScript string methods! Let me know if you have any other favorites.