Skip to content

AubreyHewes/simple-shortcode-parser

Repository files navigation

Circle CI GitHub tag (latest by date) npm (scoped) node-current (scoped) License

A Simple ShortCode Parser

Tokenizes a string to an AST of shortcode/text nodes

When rendering a string of "content" that contains so-called "shortcodes", you may want to handle the shortcodes differently. i.e. render something else. This tokenizes the given string to an AST of shortcode/text nodes allowing an intuitive structure for rendering the shortcodes.

What is a shortcode?

A "shortcode" is a name used for embedding other/generated content in user supplied content. Generally attributed to the wordpress project and look like [shortcode].

Features

  • Attribute support
    • String attribute values (i.e. quoted string value)
    • Number attribute values (i.e. unquoted number value)
    • Boolean attribute values (i.e. unquoted boolean value)
      • Default Boolean value (i.e. without a value is true)
  • Customizable start/end tags

Usage

Node

Install

npm install @hewes/shortcode
# or yarn

Use

import { parse } from "@hewes/shortcode"

parse("[shortcode]");

Produces

[
  {
    "type": "shortcode",
    "token": "[shortcode]",
    "name": "shortcode"
  }
]

Browser

Install

<script src="https://unpkg.com/@hewes/shortcode"></script>
<!-- note: specify version to ensure your code expectancies -->

Use

<script>
  SimpleShortCodeParser.parse("[shortcode]");
</script>

Produces

[
  {
    "type": "shortcode",
    "token": "[shortcode]",
    "name": "shortcode"
  }
]

Examples

See Examples

Credits