Skip to content

Instantly share code, notes, and snippets.

@gheoan
Last active June 17, 2016 10:36
Show Gist options
  • Save gheoan/8f26a3a66ad671688ef2b4b6fc446d87 to your computer and use it in GitHub Desktop.
Save gheoan/8f26a3a66ad671688ef2b4b6fc446d87 to your computer and use it in GitHub Desktop.
minecraft text formatting
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<textarea id="input">
§nMinecraft Formatting
§r§00 §11 §22 §33
§44 §55 §66 §77
§88 §99 §aa §bb
§cc §dd §ee §ff
§r§0k §kMinecraft
§rl §lMinecraft
§rm §mMinecraft
§rn §nMinecraft
§ro §oMinecraft
§rr §rMinecraft
</textarea>
<div id="output" style="white-space: pre;"></div>
<script src="https://cdn.rawgit.com/tc39/proposal-string-pad-start-end/master/polyfill.js"></script>
<script src="script.js"></script>
</body>
</html>
const tokenStart = '§';
class Token {
constructor(text, type) {
this.text = text;
this.type = type;
}
}
function parse(text) {
const tokens = [];
const { length } = text;
let i = 0;
while(i < length) {
const char = text[i];
if(char === tokenStart) {
const start = i;
const type = text[++i];
while(text[i] !== tokenStart && i < length) {
i++;
}
tokens.push(new Token(text.slice(start + 2, i), type));
} else {
const start = i;
while(text[i] !== tokenStart && i < length) {
i++;
}
tokens.push(new Token(text.slice(start, i), null));
}
}
return tokens;
}
function render(tokens, outputElement) {
outputElement.innerHTML = '';
function createAndAttachElement(text, tag) {
const element = document.createElement(tag);
element.textContent = text;
outputElement.appendChild(element);
}
const { length } = tokens;
for(let i = 0; i < length; i++) {
const token = tokens[i];
let { text, type } = token;
switch (type) {
case 'k':
// obfuscate
break;
case 'l':
// bold
createAndAttachElement(text, 'strong');
break;
case 'm':
createAndAttachElement(text, 's');
break;
case 'n':
createAndAttachElement(text, 'u');
break;
case 'o':
createAndAttachElement(text, 'i');
break;
case 'r':
createAndAttachElement(text, 'span');
break;
default:
createAndAttachElement(text, 'span');
break;
}
}
}
const inputElement = document.getElementById('input');
inputElement.addEventListener('input', () => {
render(parse(inputElement.value), document.getElementById('output'));
});
inputElement.dispatchEvent(new CustomEvent('input'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment