Skip to content

Instantly share code, notes, and snippets.

@guyht
Created December 30, 2011 19:05
Show Gist options
  • Save guyht/1541065 to your computer and use it in GitHub Desktop.
Save guyht/1541065 to your computer and use it in GitHub Desktop.
var worker = new Worker('worker.js');
function parseWiki(_w) {
var t;
// Parse the wiki data
t = _w.replace(/=====(.*?)=====/g, '<h5>$1</h5>');
t = t.replace(/====(.*?)====/g, '<h4>$1</h4>');
t = t.replace(/===(.*?)===/g, '<h3>$1</h3>');
t = t.replace(/==(.*?)==/g, '<h2>$1</h2>');
t = t.replace(/=(.*?)=/g, '<h1>$1</h1>');
t = t.replace(/\*(.*?)\*/g, '<b>$1</b>');
t = t.replace(/\_(.*?)\_/g, '<i>$1</i>');
t = t.replace(/\n/g, '<br />' );
// Return the parsed data
return t;
}
worker.onmessage = function(event) {
alert(event.data);
}
worker.postMessage('Message for worker');
self.onmessage = function(event) {
self.postMessage(event.data);
};
<html>
<head>
<title> Wiki </title>
</head>
<body onload='init()'>
<div id='wiki_div'></div>
<textarea id='wiki_textarea' onkeyup='parse(this)' cols='100' rows='20'></textarea>
</body>
</html>
<script type="text/javascript">
function init() {
document.parser = new Worker('Parser.js');
document.parser.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
document.parser.onmessage = function(event) {
document.getElementById('wiki_div').innerHTML = event.data;
};
document.parser.postMessage(document.getElementById('wiki_textarea').value);
}
function parse(obj) {
document.parser.postMessage(obj.value);
}
</script>
document.parser.onerror = function(event){
throw new Error(event.message + " (" + event.filename + ":" + event.lineno + ")");
};
/*
* This is a Javascript Worker to parse wiki code into HTML
*
* The script will parse the following:
* ===== Level 5 Title ===== -> <h5>Level 5 Title</h5>
* ==== Level 4 Title ==== -> <h4>Level 4 Title</h4>
* === Level 3 Title === -> <h3>Level 3 Title</h3>
* == Level 2 Title == -> <h2>Level 2 Title</h2>
* = Level 1 Title = -> <h1>Level 1 Title</h1>
* *Bold* -> <b>Bold</b>
* _Italic_ -> <i>Italic</i>
*/
// Recieve message
self.onmessage = function(event) {
self.postMessage(parseWiki(event.data));
};
/*
* Function to parse the wiki text and return the html.
*
* _w - The wiki text
*
* returns - String containing parsed HTML
*
*/
function parseWiki(_w) {
var t;
// Parse the wiki data
t = _w.replace(/=====(.*?)=====/g, '<h5>$1</h5>');
t = t.replace(/====(.*?)====/g, '<h4>$1</h4>');
t = t.replace(/===(.*?)===/g, '<h3>$1</h3>');
t = t.replace(/==(.*?)==/g, '<h2>$1</h2>');
t = t.replace(/=(.*?)=/g, '<h1>$1</h1>');
t = t.replace(/\*(.*?)\*/g, '<b>$1</b>');
t = t.replace(/\_(.*?)\_/g, '<i>$1</i>');
t = t.replace(/\n/g, '<br />' );
// Return the parsed data
return t;
}
self.onmessage = function(event) {
self.postMessage(parseWiki(event.data));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment