Split
Consider a string
that has many parts. It has a delimiter character that we want to split upon. With split()
in Node.js we have many ways to do this.
Often, the best approach is the simplest. With a single character delimiter, we can write simple code to split the string
. Sometimes a regular expression is needed.
Here we introduce a string
literal that has 4 substring separated with a plus delimiter. The "plus" character separates 4 color names.
string
argument: the "+" char
.string
so there are fewer delimiters than strings.string
for each color word.var colors = "blue+orange+red+yellow"; // Part 1: split on the plus. var result = colors.split("+"); // Part 2: write the length. console.log("SPLIT RESULT LENGTH: " + result.length); // Part 3: write each resulting string. for (var i = 0; i < result.length; i++) { console.log("SPLIT RESULT: " + result[i]); }SPLIT RESULT LENGTH: 4 SPLIT RESULT: blue SPLIT RESULT: orange SPLIT RESULT: red SPLIT RESULT: yellow
Regex
Sometimes we need a more complex approach to separating strings. We can use a regular expression. Here we split on one or more non-word characters (like spaces or newlines).
var data = "cat bird frog"; // Split on one or more non-word characters. // ... This includes spaces and newlines. var results = data.split(/\W+/); console.log("SPLIT NON-WORD: " + results);SPLIT NON-WORD: cat,bird,frog
With split()
and a regular expression we can get the numbers from a string
. We split on non-digit characters. The uppercase "D+" means one or more non-digit chars.
Number()
to convert the strings to actual numeric values.var input = "0 cat 10(20)30-500"; // Split on no none or more non-digit chars. var numberStrings = input.split(/\D+/); // Convert all strings into Numbers. // ... Write them. for (var i = 0; i < numberStrings.length; i++) { var number = Number(numberStrings[i]); console.log("NUMBER: " + number); }NUMBER: 0 NUMBER: 10 NUMBER: 20 NUMBER: 30 NUMBER: 500
We can split on a set of characters—here we have 3 char
delimiters, and we split a string
on all of them in a single call. We use a character set in the regular expression.
// This string has multiple delimiter chars. var codes = "100x200y300z400"; // Split on a set of characters at once. var results = codes.split(/[xyz]/); // Display results. for (var i = 0; i < results.length; i++) { console.log("RESULT: " + results[i]); }RESULT: 100 RESULT: 200 RESULT: 300 RESULT: 400
Splitting a string
is a common operation in nearly all languages. When we call Split
, we receive an array of the parts that were separated by a delimiter.