Skip to content

Instantly share code, notes, and snippets.

@CyberAP
Created March 10, 2021 00:31
Show Gist options
  • Select an option

  • Save CyberAP/0fd25e433be0b62b46c868b253143200 to your computer and use it in GitHub Desktop.

Select an option

Save CyberAP/0fd25e433be0b62b46c868b253143200 to your computer and use it in GitHub Desktop.
Convert html-like translation strings into scoped-slot-compatible chunks
/*
* "foo<bar>baz</bar>qux" => ['foo', ['bar', 'baz'], 'qux']
* "<bar/>" => [['bar', '']]
* */
function parseStringIntoChunks(string) {
const chunks = [];
let buffer = '';
let currentTag = '';
let currentTagContent = '';
let isTagToken = false;
let isContent = false;
for (let i = 0; i < string.length; i += 1) {
const token = string[i];
if (token === '<') {
isTagToken = true;
// Если мы закончили набивать контент то закрывающий тег можно скипнуть
if (isContent) {
chunks.push([currentTag, currentTagContent]);
i += currentTag.length + 2;
currentTag = '';
currentTagContent = '';
isTagToken = false;
isContent = false;
} else if (buffer) {
chunks.push(buffer);
buffer = '';
isTagToken = true;
}
continue;
}
if (token === '>') {
isTagToken = false;
isContent = true;
continue;
}
// Самозакрывающийся тег
if (token === '/' && isTagToken) {
isTagToken = false;
isContent = false;
chunks.push([currentTag.trim()]);
currentTag = '';
i += 1;
continue;
}
if (isTagToken) {
currentTag += token;
} else if (isContent) {
currentTagContent += token;
} else {
buffer += token;
}
}
if (buffer) chunks.push(buffer);
return chunks;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment