Using the split and join Methods in JavaScript

Turning strings into arrays and back again with split and join.

There are times when you need to work with the pieces of a string, like the words in a sentence or the values in a comma-separated list. Strings don't have most of the handy methods arrays do, so the trick is to turn the string into an array with split, do your work, and turn it back into a string with join.

split

split breaks a string into an array wherever it finds the separator you pass in:

const tags = "javascript,react,css"
tags.split(",") // ["javascript", "react", "css"]
"Hello world from JS".split(" ") // ["Hello", "world", "from", "JS"]
"hello".split("") // ["h", "e", "l", "l", "o"]

An empty string as the separator splits the string into single characters. If the separator isn't found, you get back an array with the whole string in it.

You can also pass a limit as the second argument:

"a,b,c,d".split(",", 2) // ["a", "b"]

join

join does the opposite. It glues the items of an array together into one string, with the separator you pass in between each one:

const words = ["Hello", "world"]
words.join(" ") // "Hello world"
words.join("-") // "Hello-world"
words.join("") // "Helloworld"
words.join() // "Hello,world"

With no separator, join uses a comma.

Using Them Together

Split and join together make a quick way to swap one character for another:

"2020-04-21".split("-").join("/") // "2020/04/21"

Since you have an array in the middle, you can use any array method on the way through. Here's a function that turns a post title into a URL slug:

const slugify = (title) =>
title
.toLowerCase()
.split(" ")
.filter((word) => word !== "")
.join("-")
slugify("Using the split and join Methods") // "using-the-split-and-join-methods"

The filter drops the empty strings left behind by double spaces.

And one that capitalizes every word, using map:

const capitalize = (sentence) =>
sentence
.split(" ")
.map((word) => word[0].toUpperCase() + word.slice(1))
.join(" ")
capitalize("front end web development tips") // "Front End Web Development Tips"

Split it, change it, join it. That pattern covers a lot of everyday string work.

Have some feedback on this post? .