JavaScript String split() Method

Beginner
⏱️ 10 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Instance method

What You’ll Learn

String.prototype.split() divides a string into an array of substrings by searching for a separator pattern (same API as MDN String.prototype.split()). Learn string and regex separators, the optional limit, capturing groups, empty edges, five examples, and try-it labs.

01

Kind

Instance method

02

Returns

Array of strings

03

Separator

String or RegExp

04

Limit

Optional cap

05

Mutates?

No

06

Baseline

Widely available

Introduction

Need words from a sentence, columns from a CSV line, or path segments from a URL? split() cuts the string wherever a separator matches and returns an array of the pieces.

The separator can be a string (like " " or ",") or a regular expression. An optional limit stops after a fixed number of pieces. The original string never changes.

💡
Beginner tip

split and join are partners: "a-b-c".split("-") gives ["a","b","c"], and ["a","b","c"].join("-") puts them back together.

This page is part of JavaScript String Methods. Related topics include slice() and search().

Understanding the split() Method

str.split(separator, limit) searches for separator and builds an ordered array of the text between matches. The separator itself is usually left out (unless a regex capturing group pulls parts of it back in).

  • Returns a new array; the original string is unchanged.
  • Omit separator to get a one-element array with the whole string.
  • Use "" to split into individual code units (see Unicode note below).
  • Use limit when you only need the first few pieces.

📝 Syntax

General form of String.prototype.split:

JavaScript
str.split(separator)
str.split(separator, limit)

Parameters

  • separator — where to cut. A string, a RegExp, or an object with Symbol.split. Omit / pass undefined to return [str]. Other values are coerced to strings.
  • limit (optional) — non-negative integer capping how many substrings to include. Leftover text is discarded. 0 returns [].

Return value

An Array of strings (regex capturing groups may also insert matched pieces):

SituationResult
Separator foundPieces between matches
Separator omitted / undefined[wholeString]
Separator not foundOne-element array with the whole string
separator === ""Array of UTF-16 code units
limit providedAt most limit entries
"".split("")Empty array []

Common patterns

JavaScript
"a,b,c".split(",");     // ["a", "b", "c"]
"one two".split(" ");   // ["one", "two"]
"hello".split("");      // ["h", "e", "l", "l", "o"]
"keep whole".split();   // ["keep whole"]
"a-b-c-d".split("-", 2); // ["a", "b"]

⚡ Quick Reference

GoalCode
Words in a sentencestr.split(" ")
CSV columnsline.split(",")
Characters (BMP)str.split("")
First n piecesstr.split(sep, n)
Flexible delimiterstr.split(/\s*,\s*/)
Join backarr.join(sep)

🔍 At a Glance

Four facts to remember about String.split().

Returns
Array

Ordered substrings

Separator
string | RegExp

Where to cut

Limit
optional

Caps array length

Mutates
no

Original stays intact

📋 split() vs slice() vs join()

split()slice()join()
Works onStringString (or Array)Array
ReturnsArray of piecesOne substringOne string
Best forDelimiter-based cutsIndex-based extractRecombine pieces
Partnerjoin()split()

Examples Gallery

Examples follow MDN String.split() patterns. Use View Output or Try It Yourself for each case.

📚 Getting Started

Words, characters, and copying the whole string.

Example 1 — Basic split()

MDN demo: split a pangram by spaces, by empty string, or with no separator.

JavaScript
const str = "The quick brown fox jumps over the lazy dog.";

const words = str.split(" ");
words[3];
// "fox"

const chars = str.split("");
chars[8];
// "k"

const strCopy = str.split();
// ["The quick brown fox jumps over the lazy dog."]
Try It Yourself

How It Works

split(" ") cuts on every space. split("") yields code units. No argument keeps the string as a single array element.

Example 2 — CSV Months and Empty Edges

Comma-separated values, plus MDN empty-string edge cases.

JavaScript
const monthString = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec";
monthString.split(",");
// 12 month abbreviations

"".split("a");  // [""]  — empty string, non-empty separator
"".split("");   // []    — both empty

"a,,c".split(",");
// ["a", "", "c"]  — consecutive separators create empty pieces
Try It Yourself

How It Works

Each match of the separator starts a new piece. Two commas in a row mean an empty string sits between them — useful for sparse CSV fields.

📈 Practical Patterns

Limits, regex separators, and everyday parsing.

Example 3 — Limit the Number of Pieces

MDN demo: stop after a fixed number of splits.

JavaScript
const myString = "Hello World. How are you doing?";
myString.split(" ", 3);
// ["Hello", "World.", "How"]

"a-b-c-d".split("-", 0);
// []

"a-b-c-d".split("-", 1);
// ["a"]
Try It Yourself

How It Works

After limit entries are collected, splitting stops and the rest of the string is not included. Use this for “first token only” style parsing.

Example 4 — Regex Separator and Capturing Groups

MDN demos: flexible delimiters, and keeping matched digits in the result.

JavaScript
const names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
names.split(/\s*(?:;|$)\s*/);
// ["Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", ""]

const myString = "Hello 1 word. Sentence number 2.";
myString.split(/(\d)/);
// ["Hello ", "1", " word. Sentence number ", "2", "."]
Try It Yourself

How It Works

A regex can ignore uneven spaces around ;. Capturing parentheses (\d) splice each matched digit into the array between the pieces.

Example 5 — Paths, Emails, and Join

Everyday parsing helpers built with split and join.

JavaScript
function fileName(path) {
  const parts = path.split("/");
  return parts[parts.length - 1];
}

function domainOf(email) {
  return email.split("@")[1];
}

fileName("views/js/string/methods/split.ejs");
// "split.ejs"

domainOf("hello@codetofun.com");
// "codetofun.com"

["a", "b", "c"].join("-");
// "a-b-c"
Try It Yourself

How It Works

Split on a known delimiter, pick the piece you need, and use join when you want a string again.

🚀 Common Use Cases

  • Tokenize text — words, tags, or CSV columns.
  • Parse paths / URLs — split on / or ?.
  • Read config lines — cut key/value pairs on = or :.
  • Take a prefix of tokens — use the limit argument.
  • Not for index windows — use slice() when you know start/end indexes.
  • Not for emoji-safe chars — prefer Array.from(str) over split("") for Unicode code points.

🧠 How split() Builds the Array

1

Read separator / limit

Treat missing separator as “keep whole string.”

Input
2

Find matches

Locate each separator (string or regex) in order.

Search
3

Collect pieces

Push text between matches (plus captures if any).

Build
4

Return an array

Stop early if limit is reached; original str unchanged.

📝 Notes

  • The separator is usually not included in the result (except regex capturing groups).
  • split("") splits UTF-16 code units — emoji may break into surrogates.
  • Leading/trailing separators create empty strings at the ends of the array.
  • limit discards leftover text; it does not append a “remainder” piece.
  • Pair with join() to rebuild a string from pieces.
  • Always capture the returned array — the original string is unchanged.

Browser & Runtime Support

String.prototype.split() is Baseline Widely available — supported across modern browsers since July 2015 (and far earlier as a core language feature).

Baseline · Widely available

String.split()

Safe for production in browsers and runtimes (Node.js, Deno, Bun). Prefer split() for delimiter-based tokenization.

Universal Widely available
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
split() Excellent

Bottom line: Use String.split() to turn text into an array of pieces. Remember limit discards leftovers, and split("") is UTF-16 — not grapheme-safe.

Conclusion

String.prototype.split() is the go-to tool for turning delimited text into an array — spaces, commas, regex patterns, and optional limits included. Combine it with join() when you need a string again, and prefer slice() when you already know indexes.

Continue with substr(), slice(), or the String methods hub.

💡 Best Practices

✅ Do

  • Use string separators for simple delimiters
  • Use regex when spacing around delimiters varies
  • Pass limit when you only need the first tokens
  • Filter empty pieces when consecutive separators appear
  • Use Array.from(str) for Unicode-aware “characters”

❌ Don’t

  • Expect limit to keep a remainder chunk
  • Use split("") on emoji without checking surrogates
  • Forget trailing empties from ending separators
  • Mutate strings — always use the returned array
  • Parse complex CSV with naive split(",") (quotes break it)

Key Takeaways

Knowledge Unlocked

Five things to remember about String.split()

Divide a string into an array of substrings.

5
Core concepts
✂️ 02

Separator

string / regex

Input
🔢 03

Limit

optional cap

Control
🔁 04

Partner

join()

Pair
05

Mutates

no

Immutable

❓ Frequently Asked Questions

String.prototype.split(separator, limit?) divides a string into an ordered list of substrings and returns them in an Array. The original string is unchanged.
Omitting separator (or passing undefined) returns a one-element array containing the whole string — for example "hi".split() is ["hi"].
An empty-string separator splits into UTF-16 code units (roughly “characters” for BMP text). Be careful with emoji — surrogate pairs can break. Prefer Array.from(str) or [...str] for Unicode code points.
limit is a non-negative integer capping how many pieces go into the array. Leftover text is discarded. limit 0 returns [].
Yes. Pass a RegExp as separator. If the regex has capturing groups, those captures are included in the result array.
Use Array.prototype.join(). For example "a,b,c".split(",").join("-") returns "a-b-c".
Did you know?

"".split("") is the only way to get an empty array when the separator is a string and limit is not 0. And if a regex separator has capturing groups, those captures are spliced into the result — a feature many beginners discover by accident.

More String Methods

Return to the hub for slice, trim, replace, and more.

String methods hub →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful