UNPKG

@gitlab/ui

Version:
65 lines (53 loc) 1.59 kB
/** * Split the given string after each occurrence of each of the given symbols. * * Symbols are strings, and can be of length one or more. Zero-length symbols * are ignored. * * Unlike with `String::split`, the symbol is left in results, with * the split occurring _after_ the symbol. * * For example: * * splitAfterSymbols(['/'], 'a/b/c') // ['a/', 'b/', 'c'] * splitAfterSymbols(['foo'], 'foobar') // ['foo', 'bar'] * * @param {string[]} symbols The symbols to split the string by. * @param {string} string The string to split. * @returns {string[]} The resulting strings. */ var splitAfterSymbols = function splitAfterSymbols(symbols, string) { var textParts = []; var textPartStartIndex = 0; if (string.length === 0) { return [string]; } for (var i = 0; i < string.length;) { var symbolFound = false; for (var j = 0; j < symbols.length; j += 1) { var symbol = symbols[j]; if (!symbol) { // eslint-disable-next-line no-continue continue; } symbolFound = string.slice(i, i + symbol.length) === symbol; if (symbolFound) { var textPartEndIndex = i + symbol.length; var textPart = string.slice(textPartStartIndex, textPartEndIndex); textParts.push(textPart); textPartStartIndex = textPartEndIndex; i = textPartStartIndex; break; } } if (!symbolFound) { i += 1; } } var final = string.slice(textPartStartIndex); if (final) { textParts.push(final); } return textParts; }; export { splitAfterSymbols };