splitargs2
Version:
Splits a string into tokens by a given separator, treating any quoted parts as a single token.
49 lines (41 loc) • 2.09 kB
JavaScript
/*
Copyright 2018 Shinobu1337
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/**
* Splits a string into tokens by a given separator, treating any quoted parts as a single token.
*
* @param {string} input The string to tokenize.
* @param {boolean} keepQuotes If true, quoted tokens will maintain their quote characters. Default: `false`.
* @param {RegExp} separator Matches separators for tokens. Default: `/\s/g`.
* @returns {string[]} The tokens extracted from *text*.
*/
function splitargs(input, keepQuotes = false, separator = /\s/g) {
let doubleQuoteOpen = false;
let tokens = [];
let ret = [];
const arr = input.split(''); // split the string into an array of characters
for (const element of arr) {
let matches = element.match(separator);
if (element === '"') {
if (keepQuotes) tokens.push(element);
doubleQuoteOpen = !doubleQuoteOpen;
continue;
}
if (!doubleQuoteOpen && matches) {
if (tokens.length > 0) {
ret.push(tokens.join(''));
tokens.splice(0); // clear tokens array
} else if (!!separator) {
ret.push(element);
}
} else {
tokens.push(element);
}
}
if (tokens.length > 0) ret.push(tokens.join(''));
else if (!!separator) ret.push('');
return ret;
}
module.exports = splitargs;