Split string

3 snippets across 3 stacks - JavaScript, Python, Regular Expressions

JSJavaScript

Split and Join

JS · Strings
Syntax
str.split(separator, limit)
arr.join(separator)
Example
const tags = "js,react,node";
const tagArray = tags.split(",");
console.log(tagArray);
console.log(tagArray.join(" + "));
Output
["js", "react", "node"]
"js + react + node"

Note split("") splits into individual characters. split() with no arguments returns the entire string in a single-element array.

PYPython

Join & Split

PY · Strings
Syntax
separator.join(iterable)
str.split(separator)
Example
words = ["Python", "is", "great"]
sentence = " ".join(words)
print(sentence)

csv_row = "alice,30,engineer"
fields = csv_row.split(",")
print(fields)
Output
Python is great
['alice', '30', 'engineer']

Note split() with no arguments splits on any whitespace and removes empty strings. split(',') keeps empty strings between consecutive delimiters.

RXRegular Expressions

JS: split() with Regex

RX · String Operations with Regex
Syntax
string.split(/pattern/)
Example
'one, two;  three|four'.split(/[,;|]\s*/)
Output
["one", "two", "three", "four"]

Note Split accepts a regex as the separator. If the regex contains capturing groups, the captured text is included in the result array. This can be surprising -- use non-capturing groups (?:) if you don't want separator parts in the output.

Frequently asked questions

How do you split string?
This task is covered in 3 stacks on this page: JavaScript, Python, Regular Expressions. The "Split and Join" snippet in JavaScript uses `str.split(separator, limit)`.
Which code does the JavaScript example use?
The "Split and Join" snippet uses `str.split(separator, limit)`, from the Strings section of the JavaScript cheat sheet.
Which stacks cover "split string" on this page?
JavaScript, Python, Regular Expressions. Together they hold 3 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Split and Join": split("") splits into individual characters. split() with no arguments returns the entire string in a single-element array.