How to Split a String into an Array in JavaScript

How to Split a String into an Array in JavaScript

In this JavaScript split string tutorial, you'll learn how to split a string into an array in JavaScript. A string is a data structure that represents a sequence of characters, and an array is a data structure that contains multiple values. A string can be broken apart into an array of multiple strings using the split method. The split() method is used to split a string into an array of substrings, and returns the new array.

A string is a data structure that represents a sequence of characters, and an array is a data structure that contains multiple values.

And did you know – a string can be broken apart into an array of multiple strings using the split method. Let's see how that works with some examples.

TL;DR

If you just want the code, here you go:

const publisher = 'free code camp'
publisher.split(' ') // [ 'free', 'code', 'camp' ]

Syntax

According to the MDN, the syntax you'll need to split the string is str.split([separator[, limit]]). If we apply this to the above example:

  • str is publisher
  • separator is ' '
  • there is no limit

When do you need to split a string?

Example 1: getting part of a string

Here is a common example which involves getting the token from an auth header that is part of a Token-based Authentication System.

If this doesn't mean anything to you that's ok. All you need to know for the following example is that there is a string with the value bearer token, but only token is needed (as this is the part that identifies the user):

const authHeader = 'bearer token'
const split = authHeader.split(' ') // (1) [ 'bearer', 'token' ]
const token = split[1] // (2) token

Here's what's happening in the above code:

  1. The string is split with ' ' as the separator
  2. The second entry in the array is accessed

Example 2: apply array methods to a string

Often the input you are given is a string, but you want to apply array methods to it (eg. map, filter, or reduce).

For example, let's say you are given a string of morse code and you want to see what it reads in English:

const morse = '-.-. --- -.. .'
// (1)
const morseToChar = {
  '-.-.': 'c',
  '-..': 'd',
  '.': 'e',
  '---': 'o',
}

const morseArray = morse.split(' ') // (2) [ '-.-.', '---', '-..', '.' ]
const textArray = morseArray.map((char) => morseToChar[char]) // (3) [ 'c', 'o', 'd', 'e' ]
const text = textArray.join() // (4)

Here's what's happening in the above code:

  1. An object literal is created to map morse chars to the English alphabet
  2. The morse code is split into an array with a ' ' as the separator. (Without ' ' as an argument you would end up with an array that has separate entries for each . and -.)
  3. The morse code array is mapped/transformed to a text array
  4. A string is created from the array with '' as the separator. (Without '' as an argument the output would be c,o,d,e.)

How to add a limit to split

According to the MDN, it is also possible to pass a limit as an argument to split. I have never needed to do this, but here is how you could apply it:

const publisher = 'free code camp'
publisher.split(' ', 1) // [ 'free' ]

In the above example, the array is limited to one entry. Without it the value of the array would be [ 'free', 'code', 'camp' ].

Before you go…

Thank you for reading this far! I write about my professional and educational experiences as a self-taught software developer, so feel free to check out my website or subscribe to my newsletter for more content.

You might also like:

The Original Article can be found on freecodecamp.org

javascript programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Learning JavaScript: Development Environments for JavaScript Programming

One of the nice things about learning JavaScript these days is that there is a plethora of choices for writing and running JavaScript code. In this article, I’m going to describe a few of these environments and show you the environment I’ll be using in this series of articles.

How long does it take to develop/build an app?

This article covers A-Z about the mobile and web app development process and answers your question on how long does it take to develop/build an app.

JavaScript Tutorial: How To Create Your First JavaScript Program

In this JavaScript tutorial for beginners, we will learn how to write your first JavaScript Program, we will follow the below steps: Create a html page, Add JavaScript in the page – Inline, Add JavaScript in the page – External, Check the Developer Console in the browser

Developer Career Path: To Become a Team Lead or Stay a Developer?

For a developer, becoming a team leader can be a trap or open up opportunities for creating software. Two years ago, when I was a developer, ... by Oleg Sklyarov, Fullstack Developer at Skyeng company

ReactJS: The Javascript Developer’s Guide

This article will walk you through the concepts you would need to know to step into the world of widely used ReactJS.