splitFields
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
strString: Input text to split.optionsObject: Optional configuration object. The current implementation accepts the parameter but does not use it.
Return value
String[]
Usage example
| |
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
TypeErroris 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