export function *tokenize (text: string, sep: string) { if (!text) { return; } let start = 0; for(;;) { const index = text.indexOf(sep, start); if (index === -1) { break; } yield text.substring(start, index); start = index + sep.length; } yield text.substring(start); }; export function tokenizeMax(text: string, sep: string, max = Number.MAX_SAFE_INTEGER) { if (!text) { return []; } let start = 0; const items = []; max--; for(;;) { const index = text.indexOf(sep, start); if (index === -1) { break; } items.push(text.substring(start, index)); start = index + 1; if (--max === 0) { break; } } items.push(text.substring(start)); return items; }; export function *tokenizeRegex(text: string, regex: RegExp) { if (!text) { return; } regex.lastIndex = 0; let m; while((m = regex.exec(text)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } if (m?.length) { yield m as RegExpExecArray; } } } export function *tokenizeRegexAll(text: string, regex: RegExp) { if (!text) { return; } regex.lastIndex = 0; let start = 0; for(const m of text.matchAll(regex)) { if (start < m.index) { yield { text: text.substring(start, m.index)}; } yield { match: m }; start = m.index + m[0].length; } if (start < text.length) { if (start) { yield { text: text.substring(start) }; } else { yield { text }; } } // let m; // let start = 0; // while((m = regex.exec(text)) !== null) { // const { lastIndex } = regex; // if (m.index === lastIndex) { // regex.lastIndex++; // } // if (!m?.length) { // break; // } // if (start < m.index) { // yield { text: text.substring(start, m.index)}; // } // yield { match: m as RegExpExecArray }; // start = m.index + m[0].length; // } // if (start < text.length) { // yield { text: text.substring(start) }; // } } export function *tokenizeCssUrl(html: string) { const set = new Set(); for(const match of tokenizeRegex(html, /url\(((\"[^\"]+\")|(\'[^\']+\')|([^\)]+))\)/gmi)) { const value = match[1]; if (!value) { continue; } if (set.has(value)) { continue; } set.add(value); yield value; } }