How to Convert a String to an Array in TypeScript?

In this tutorial, I will explain how to convert a string to an array in TypeScript. As a developer, I often encounter situations where manipulating strings and arrays is crucial. Recently, while working on a project for a client in New York, I needed to split a large CSV string into an array of values for easier manipulation.

Methods to Convert String to Array in TypeScript

TypeScript, being a superset of JavaScript, inherits all the string manipulation methods available in JavaScript. Here are some commonly used methods to convert a string to an array in Typescript.

1. Using split() Method

The split() method is one of the most straightforward ways to convert a string to an array in Typescript. It splits a string into an array of substrings based on a specified delimiter. Let me show you an example.

Example:

Let’s say we have a string of city names in the USA separated by commas:

const cities = "New York,Los Angeles,Chicago,Houston,Phoenix";
const cityArray = cities.split(",");
console.log(cityArray); // Output: ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]

In this example, the split() method splits the cities string at each comma, resulting in an array of city names.

Here is the exact output in the screenshot below:

Convert String to Array in TypeScript

Read Calculate the Sum of an Array in TypeScript

2. Using Array.from()

The Array.from() method in Typescript creates a new array instance from an array-like or iterable object. When used with a string, it converts each character of the string into an array element.

Here is an example.

Example:

Consider a string representing a phone number:

const phoneNumber = "123-456-7890";
const phoneArray = Array.from(phoneNumber);
console.log(phoneArray); // Output: ["1", "2", "3", "-", "4", "5", "6", "-", "7", "8", "9", "0"]

In this example, Array.from() converts each character of the phoneNumber string into an array element, including the hyphens.

Check out Clear an Array in TypeScript While Preserving Its Type

3. Using Spread Operator

The spread operator (...) in Typescript can also be used to convert a string into an array. It spreads the characters of the string into individual array elements.

Example:

Let’s convert a string containing a zip code:

const zipCode = "90210";
const zipArray = [...zipCode];
console.log(zipArray); // Output: ["9", "0", "2", "1", "0"]

In this example, the spread operator spreads the characters of the zipCode string into an array.

Here is the exact output in the screenshot below:

TypeScript Convert String to Array

Read How to Reverse an Array in TypeScript?

4. Using Object.assign()

The Object.assign() method can be used to convert a string into an array by assigning the characters of the string to an array-like object.

Here is an example and the complete Typescript code.

Example:

Let’s convert a string representing a social security number:

const ssn = "123-45-6789";
const ssnArray = Object.assign([], ssn);
console.log(ssnArray); // Output: ["1", "2", "3", "-", "4", "5", "-", "6", "7", "8", "9"]

In this example, Object.assign() assigns each character of the ssn string to an array element.

5. Using for…of Loop

A more manual approach involves using a for...of loop to iterate over each character of the string and push it into an array in Typescript.

Example:

Consider a string representing a date in the format MM/DD/YYYY:

const date = "11/14/2024";
const dateArray: string[] = [];
for (const char of date) {
    dateArray.push(char);
}
console.log(dateArray); // Output: ["1", "1", "/", "1", "4", "/", "2", "0", "2", "4"]

In this example, the for...of loop iterates over each character of the date string and pushes it into the dateArray.

Convert a String to an Array in TypeScript Examples

Now, let me show you two practical examples of converting a string to an array in TypeScript.

Parse CSV Data

A common use case for converting strings to arrays is parsing CSV data in TypeScript. For instance, let’s say we have a CSV string of user data:

const csvData = "John Doe,30,New York\nJane Smith,25,Los Angeles\nMike Johnson,35,Chicago";
const rows = csvData.split("\n");
const users = rows.map(row => row.split(","));
console.log(users);
// Output: [["John Doe", "30", "New York"], ["Jane Smith", "25", "Los Angeles"], ["Mike Johnson", "35", "Chicago"]]

In this example, we first split the CSV string into rows using the newline character (\n). Then, we split each row into individual values using the comma (,) delimiter.

Tokenizing Sentences

Another practical use case is tokenizing sentences into words. This can be useful for text analysis or natural language processing (NLP) tasks.

Example:

const sentence = "The quick brown fox jumps over the lazy dog";
const words = sentence.split(" ");
console.log(words); // Output: ["The", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"]

In this example, the split(" ") method splits the sentence into an array of words based on spaces.

Conclusion

In this tutorial, I explained how to convert a string to an array in TypeScript using various methods such as:

  1. Using split() Method
  2. Using Array.from()
  3. Using Spread Operator
  4. Using Object.assign()
  5. Using for…of Loop