Doing the `.split()` with Javascript

I recently learned that the .split() method in Javascript can take in an optional second argument that is the number of times it’ll split a given string. It’ll ignore everything after the string has been split that number of times, even if there are additional matches.

In this post, I will explain how split() works, the arguments it takes in, and some example use cases.

Understanding .split()

If you are unfamiliar with .split() in Javascript, it is a built-in method for breaking up a string into multiple parts, based on the character(s) that you define. This is the format for .split() is as follows:

"string to split".split("character[s]_to_split_by", numTimesToSplit)

The parts that make up a valid .split() method are:

  • The string, or variable that references a string to be split. Required.
  • A character or string to use as the point of reference on where to split the string. Required.
  • A positive integer of the number of splits to make, after which .split() will stop evaluating the string. Optional.

Using the format above, if I wanted to split the string "I love tacos!" so that each word is its own string, I can do the following.

"I love tacos!".split(" ")

Which would return [ 'I', 'love', 'tacos!' ]. The original string is split on each empty space " ".

Assigning "I love tacos!" to a variable string, returns the same result.

let string = "I love tacos!"
string.split(" ")

Using the Optional limit Argument

Where I found using the optional limit argument helpful was if I wanted to split a string into separate variables, but didn’t need all of the string I was calling the function on.

Let’s say I had copy and pasted some HTML colors names, to use in an app I’m building. Each row contains the named color, it’s hex and rgb values. Picking a few samples, and putting each row as it’s own array item, we have something that looks like this.

const data = [
    "Gold #FFD700 rgb(255, 215, 0)",
    "Indigo #4B0082 rgb(75, 0, 130)",
    "Chartreuse #7FFF00 rgb(127, 255, 0)",
    "WhiteSmoke #F5F5F5 rgb(245, 245, 245)"

Splitting each array item on each word break (" "), returns this.

[ 'Gold', '#FFD700', 'rgb(255,', '215,', '0)' ]
[ 'Indigo', '#4B0082', 'rgb(75,', '0,', '130)' ]
[ 'Chartreuse', '#7FFF00', 'rgb(127,', '255,', '0)' ]
[ 'WhiteSmoke', '#F5F5F5', 'rgb(245,', '245,', '245)' ]

This works. But it’s a little messy if we don’t care about the RGB values.

If we pass in 2 as the second argument .split() will ignore everything after it’s made two split groups. If we call .split(" ", 2) on each array item, the return looks like this instead.

[ 'Gold', '#FFD700' ]
[ 'Indigo', '#4B0082' ]
[ 'Chartreuse', '#7FFF00' ]
[ 'WhiteSmoke', '#F5F5F5' ]

Use Cases

Here’s another example where using the limit argument with .split() is useful.

Let’s say we have a bunch of phone numbers as strings and we want to assign the area code to its own variable. If our phone numbers are formatted like "555-867-5309", we can split on each hyphen.

let phone = "555-867-5309"
let areaCode = phone.split("-")

It works, but now areaCode returns [ '555', '867', '5309' ]. With one small change to the above code, we can cleanly assign the area code to it’s own variable and ignore the rest of the phone number.

let phone = "555-867-5309"
let areaCode = phone.split("-", 1)

After we’ve made 1 split on the first hyphen, the .split() operation stops. areaCode now returns [ '555' ].

Additional Information

.split() can break strings into smaller parts, but here are some additional things to keep in mind.

  • You can split by more than one character
  • The character[s] to split by are case sensitive
  • Using .split() does not modify the original string
  • .split() can be used together with other built-in methods like .join()


Base64 Encoding

While browsing some API documentation, I saw references to Base64 for passing credentials to the API. I had seen Base64 referenced a few times, but had no idea how to convert text into Base64. So, I did some digging. This post will outline how to encode (and decode) text into Base64 using the MacOS Terminal.

What is Base64?

I should share a little bit about what base64 is. The MDN documentation explains the overarching concept of Base64 is.

Base64 is a group of similar binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation.

You can think of Base64 is another way to represent binary or text data.

The conversion process is somewhat detailed, and I encourage you to check out the resources at the bottom of this article if you are curious about the benefits and technical details of Base64.

Converting Text into Base64

While reading those API docs, I had no idea to create a Base64 string.

There are converters a few Google searches away. But, did you know there’s a Base64 command built into the MacOS?

To turn a string into Base64, open a new Terminal window, and use this format.

base64 <<< string

That would be base64 followed by a space, three less-than signs (<), another space, then whatever string you want to encode in Base64.

Here’s an example:

If I wanted to convert the string I love cheeseburgers into Base64, I would enter this:

base64 <<< "I love cheeseburgers"

Which would print out SSBsb3ZlIGNoZWVzZWJ1cmdlcnMK as a result.

You only need quote marks around the string you would like to convert, if it has space it in.

The following does not need quote marks, for example:

base64 <<< ilovecheeseburgers

Decoding Base64

With a similar command, you can decode Base64 back into human, readable text.

Let’s say a friend of ours sent us the following code:


To decode Base64, we add a -D flag before the three arrows and after base64.

Like this:

base64 -D <<< SSBsb3ZlIHlvdSBtb3JlCg==

Which returns I love you more. How sweet!

Base64 is Not Unique

While a Base64 string like SSBsb3ZlIGNoZWVzZWJ1cmdlcnMk looks random, it is not.

Each time I run base64 <<< "I love cheeseburgers" it’ll return the same result. If you run the same code, you’ll get the same result. And since a Base64 string can be decoded, it’s not appropriate for hashing passwords, storing API keys, etc.


Planning Your Escape from Tutorial Hell

I’ve previously written about doing tutorial based projects and how it’s not a bad thing.

What can happen, is that your project looks like everyone else’s who did the same tutorial.

Again, this is not a bad thing.

But you can take your learning a step further by adding features onto those projects.

Here are some ideas to get you started


  • Automatically deploy changes each time a git repo is updated

CRUD operations

  • If a user can create items as part of your project, can they edit them as well?


  • Migrate your backend database to Postgres and host on Heroku.
  • Automatically deploy your frontend to Netlify or Vercel.

Error handling

  • What happens if a user tries to navigate away from a page while they were filling out a form field?
  • What if there is no result from an API query?

Form validation

  • Are there any form fields are required or nullable?
  • What happens if a user enters a string when a field is only meant to access numbers?

How To

  • A blog post, video, tutorial, etc on how you built a new feature or solved a problem.


  • Give users the ability to login with Google, Facebook, etc

Offline access

  • What does a user see if there is a slow connection? Do they see a blank screen or some content?
  • Store changes in the browser with a service worker until database access is restored


  • If a user is logged in, should they be able to view assets created by another user?


  • Take a look at your code and see if there are opportunities to DRY it up.
  • Incorporate arrow functions, swap var instances for let or const, incorporate asynchronous functions.
  • Remove console.log(), debug() and TODO comments from deployed code.


  • Better rendering for mobile, dark/light mode toggle, make sure it’s accessible, etc.


  • Are there any risks of exposed API keys or sensitive user data?
  • Is CORS enabled?


  • Write test to validate functions are outputting the expected results.


  • A uses or about page can tell the story of how you build your project, technologies used, creative process, etc.

Free APIs

I’m a little obsessed with APIs.

They are fun to work with, especially for personal projects.

Here’s a list of fun, free, publically available API’s that I’ve been eyeing for potential new projects.

  • Bread Pun API – API for all your wholewheat bread bun kneads.
  • TheCocktailDB – An open, crowd-sourced database of drinks and cocktails from around the world.
  • Deck of Cards – An API where you can query, shuffle and deal decks of cards.
  • Dog API – The internet’s biggest collection of open source dog pictures.
  • Foursquare Places API – Get flexible access to global POI data and rich content from over 100K trusted sources and driven by millions of consumers.
  • GIPHY API – Ready to bring the engaging power of GIFs to your app through GIPHY?
  • NASA APIs – Multiple APIs available for use, including Mars Rover Photos.
  • OMDb API – The Open Movie Database (OMDb) API is a RESTful web service to obtain movie information, all content and images on the site are contributed and maintained by our users.
  • Open Emoji API – A free emoji API sourced directly from – always up to date. _Currently under development._
  • PokéAPI – All the Pokémon data you’ll ever need in one place, easily accessible through a modern RESTful API.
  • STAPI – A Star Trek API. It’s an open source project, that anyone can contribute to.
  • SWAPI – The Star Wars API
  • Tropical Fruit and Veg – The API provides a quick simple way to integrate information on within your own website or within a mobile application.

API Aggregate Websites

I cannot vouch for the APIs listed on these sites, but they are worth browsing if you are looking for something specific or interesting.

  • API List – A collective list of APIs.
  • Rapid API – Free Public APIs for Developers APIs

Open Graph for Personal Projects

A way to make your posts stand out on social media is to include images. According to Buffer, Tweets with images can get up to 150% more retweets. So it makes sense to include some kind of visual element instead of dropping a link and calling it a day.

For a long time, I wondered how some links I would share would automatically get nicely formatted images, headlines and links. Was it possible to implement something like that on my projects so that I automate and improve the link-sharing experience?


This functionality can be implemented using The Open Graph protocol.

I’ll walk through how I step it up on one of my projects.

Implementing Open Graph

The introduction says it well. In describing the Open Graph protocol, it says:

The Open Graph protocol enables any web page to become a rich object in a social graph.

The graph it refers to is an object that is created by including basic metadata tags in your webpage.

Your website most probably has metadata tags like <meta charset="UTF-8"> or <meta name="viewport" content="width=device-width, initial-scale=1.0">. The Open Graph tags use the same, self-closing <meta /> tag structure with some additions. Each Open Graph meta tag has a property and content attributes. The property attribute, describes or categorizes the value in the content attribute.

For Open Graph to work, there are 4 required properties for each webpage.

Those properties are:

  1. og:title
  2. og:type
  3. og:image
  4. og:url

Detailed descriptions of these tags can be found in the Basic Metadata section of the documentation. But, they make up the core elements of those media-rich posts that we see on our Twitter and Facebook feeds.
Using my project as an example, my 4 meta tags look something like this.

<meta property="og:title" content="How Many Days Until Halloween?" />
<meta property="og:type" content="website" />
<meta property="og:url" content="" />
<meta property="og:image" content="" />

Once my HTML file is pushed live, sharing the link to automatically renders the image that I specified along with a title and URL to the website.

Looking Nice

Prior to adding Open Graph, sharing the link in Discord looked like this.

An example of what the URL looks like without The Open Graph protocols

I mean, I think this site it awesome, but it’s probably not grabbing anyone else’s attention.

This is how it looks now.

How the URL looks after including an image that I specified, title and description.

Wow! That is easier to see and gives more context to a user who is just scrolling by. You can also see how the 4 required properties show up in the social media preview.


What I like about The Open Graph Protocol is that it’s relatively easy to implement and there are additional meta tags that can be added for richer content examples. I included a description for my project, but there are tags that are relevent for dated content like blog posts are articles.

I reccomend giving The Open Graph protocol a try so that your projects can better stand out on social media.