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.