Skip to content

Instantly share code, notes, and snippets.

@plugnburn
Last active September 8, 2022 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plugnburn/c1f577ff329e707bb609 to your computer and use it in GitHub Desktop.
Save plugnburn/c1f577ff329e707bb609 to your computer and use it in GitHub Desktop.
Micromark engine

Micromark: probably the smallest JS framework to create your own text markup languages

Overview

Have you ever dreamed of creating your own simple text markup language without all the overhead of existing parsers? Now it is possible thanks to this tiny function. Define your own rules for substituting your own character tags with HTML markup and pass them to Micromark along with your text, and it will return ready HTML code.

How to use the engine

Call the function like this:

outHTML = micromark(your_string, rules_object);

where your_string is the text written in your own text markup language, and rules_object is the object of the following syntax: {"T":"<tag1>$1</tag1>","L":"<a href=\"$1\">$2</a>"} etc.

Each element maps a tag (which must be a single character) to a substitution string with 1 or 2 parameters ($1 and $2). For 1-parameter tag, the source text is specified as Tparam1T, where T is your tag. For 2-parameter tag, it's Tparam1Tparam2T respectively.

Real example or a working rules_object:

{
    "*":"<strong>$1</strong>",          //*boldtext* => <strong>boldtext</strong>
    "_":"<em>$1</em>",                  //_italictext_ => <em>italictext</em>
    "`":"<code>$1</code>",              //`codetext` => <code>codetext</code>
    "~":"<del>$1</del>",                //~striketext~ => <del>striketext</del>
    "@":"<a href=\"$1\">$2</b>",        //@http://example.com@Click here@ => <a href="http://example.com">Click here</a>
    "!":"<img src=\"$1\" alt=\"$2\">"   //!http://example.net/image.png!Cool photo! => <img src="http://example.net/image.png" alt="Cool photo">
}

Limitations

  • Each custom tag must consist of one character. You can use any UTF-8 compatible character to make up your tag though.
  • Current implementation allows up to 2 parameters only. This is enough for most standard HTML tags but if you look at the code and get the principle you can easily extend it up to 3 or more parameters.

Other info

Micromark is created for a larger project and will be used there along with [AsgardJS] (https://gist.github.com/plugnburn/00a107cf1f26cd5b1995). Hopefully I'll start working on it soon.

© @plugnburn 2014

micromark=function(s,t,e,k){for(k in t)e="\\"+k,s=s.replace(RegExp(e+"([^"+e+"]+)"+e+"(?:([^"+e+"]+)"+e+")?","g"),t[k]);return s}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment