Split text on more than one separator.

split-pattern `split` can use a regular expression when a string may contain different separators. A character class such as `[-; ]` lists the allowed separators.

Splitting With Patterns

text
split_pattern.js
Replay: real traced execution (multi-file project)
const text = "red blue green";
const parts = text.split(/[-; ]+/);
const count = parts.length;
const first = parts[0];
const last = parts[parts.length - 1];

console.log("count=" + count);
console.log("first=" + first);
console.log("last=" + last);
const text = "red-blue-green";
const parts = text.split(/[-; ]+/);
const count = parts.length;
const first = parts[0];
const last = parts[parts.length - 1];

console.log("count=" + count);
console.log("first=" + first);
console.log("last=" + last);
const text = "red;blue;green";blue;green";
const parts = text.split(/[-; ]+/);
const count = parts.length;
const first = parts[0];
const last = parts[parts.length - 1];

console.log("count=" + count);
console.log("first=" + first);
console.log("last=" + last);
  1. text ← red blue green, parts ← red,blue,green, count ← 3, parts.length ← 3

    1const text→ red blue green = "red blue green"; //@text="red-blue-green", "red;blue;green"2const parts→ red,blue,green = textred blue green.split(/[-; ]+/);3const count→ 3 = parts.length→ 3;4const first→ red = parts[0]→ red;5const last→ green = parts[parts.length - 1]→ green;67console.log("count=" + count3);8console.log("first=" + firstred);9console.log("last=" + lastgreen);
    outputcount=3
    first=red
    last=green
  1. text ← red-blue-green, parts ← red,blue,green, count ← 3, parts.length ← 3

    1const text→ red-blue-green = "red-blue-green";2const parts→ red,blue,green = textred-blue-green.split(/[-; ]+/);3const count→ 3 = parts.length→ 3;4const first→ red = parts[0]→ red;5const last→ green = parts[parts.length - 1]→ green;67console.log("count=" + count3);8console.log("first=" + firstred);9console.log("last=" + lastgreen);
    outputcount=3
    first=red
    last=green
  1. text ← red;blue;green, parts ← red,blue,green, count ← 3, parts.length ← 3

    1const text→ red;blue;green = "red;blue;green";2const parts→ red,blue,green = textred;blue;green.split(/[-; ]+/);3const count→ 3 = parts.length→ 3;4const first→ red = parts[0]→ red;5const last→ green = parts[parts.length - 1]→ green;67console.log("count=" + count3);8console.log("first=" + firstred);9console.log("last=" + lastgreen);
    outputcount=3
    first=red
    last=green