Skip to content

splitFields

Since v8.0.75

The util/splitFields module splits a string into fields using whitespace separators while preserving quoted substrings. It is exposed both as require('util/splitFields') and as require('util').splitFields.

splitFields()

Splits a string by space, tab, newline, and carriage return characters. Text wrapped in single or double quotes is kept as a single field.

Syntax
splitFields(str[, options])
Parameters
  • str String: Input text to split.
  • options Object: Optional configuration object. The current implementation accepts the parameter but does not use it.
Return value

String[]

Usage example

1
2
3
4
5
const { splitFields } = require('util');

console.println(JSON.stringify(splitFields('cmd "arg 1" "arg 2"')));
console.println(JSON.stringify(splitFields("hello 'world foo' bar")));
console.println(JSON.stringify(splitFields('foo\tbar\nbaz')));

Behavior

  • Consecutive whitespace is treated as a single separator.
  • Empty fields are omitted from the result.
  • Quote characters are removed from the returned values.
  • Unclosed quotes keep consuming characters until the end of the string.
  • Tabs and newlines inside quoted text are preserved.

Examples

Basic whitespace splitting:

splitFields('  foo   bar baz  ');
// ['foo', 'bar', 'baz']

Double quotes:

splitFields('hello "world foo" bar');
// ['hello', 'world foo', 'bar']

Single quotes:

splitFields("hello 'world foo' bar");
// ['hello', 'world foo', 'bar']

Mixed quoting:

splitFields("a \"b c\" d 'e f' g");
// ['a', 'b c', 'd', 'e f', 'g']

Notes

  • The input must be a string, otherwise TypeError is thrown.
  • Escape sequences inside quotes are not interpreted specially.
  • This function is useful for shell-like tokenization when full command parsing is unnecessary.
Last updated on