marked.js是一个可以在线转码Markdown的JavaScript编写的库。可以非常方便的在线编译Markdown代码为HTML并直接显示,并且支持完全的自定义各种格式。

安装

使用npm则可以直接安装:

npm install marked --save

使用

1. 使用示例

简单的使用示例:

var marked = require('marked');

console.log(marked('I am using __markdown__.'));

// Outputs:

I am using markdown.

使用默认值设置选项的示例:

var marked = require('marked');

marked.setOptions({

renderer: new marked.Renderer(),

gfm: true,

tables: true,

breaks: false,

pedantic: false,

sanitize: false,

smartLists: true,

smartypants: false

});

console.log(marked('I am using __markdown__.'));

在HTML页面使用示例:

Marked in the browser

document.getElementById('content').innerHTML =

marked('# Marked in browser\n\nRendered by **marked**.');

2. 方法解析

marked(markdownString [,options] [,callback])

markdownString string类型 - 要编译的markdown源码。

options object类型 - 选项,也可以使用marked.setOptions方法设置。

callback function类型 - 当markdownString已经被完全的异步解析完毕会调用这个函数。如果options参数被省略,这个可以作为第二个参数。

3. 选项

highlight

function类型

代码高亮的回调函数。下面的第一个例子使用node-pygmentize-bundled的异步高亮,第二个例子使用highlight.js同步高亮:

var marked = require('marked');

var markdownString = '```js\n console.log("hello"); \n```';

// pygmentize-bundled的异步高亮

marked.setOptions({

highlight: function (code, lang, callback) {

require('pygmentize-bundled')({ lang: lang, format: 'html' }, code, function (err, result) {

callback(err, result.toString());

});

}

});

// Using async version of marked

marked(markdownString, function (err, content) {

if (err) throw err;

console.log(content);

});

// highlight.js的同步高亮

marked.setOptions({

highlight: function (code) {

return require('highlight.js').highlightAuto(code).value;

}

});

console.log(marked(markdownString));

highlight arguments

code string类型 - 传给highlighter的代码块。

lang string类型 - 代码块中指定的编程语言。

callback function类型 - 当使用一个异步highlighter时要调用这个回调函数。

renderer

object类型 - 默认为new Renderer()。

一个Object,包含了渲染为HTML的函数。

重写renderer方法

renderer选项允许你使用自定义样式进行渲染。这里有一个重写标题标记渲染的例子,渲染成像GitHub一样添加一个嵌入式锚标签的样式:

var marked = require('marked');

var renderer = new marked.Renderer();

renderer.heading = function (text, level) {

var escapedText = text.toLowerCase().replace(/[^\w]+/g, '-');

return '' +

text + '';

},

console.log(marked('# heading+', { renderer: renderer }));

这个代码将会输出下面的HTML:

heading+

块级元素渲染方法

code(string code, string language)

blockquote(string quote)

html(string html)

heading(string text, number level)

hr()

list(string body, boolean ordered)

listitem(string text)

paragraph(string text)

table(string header, string body)

tablerow(string content)

tablecell(string content, object flags)

flags有下面的属性:

{

header: true || false,

align: 'center' || 'left' || 'right'

}

行内元素渲染方法

strong(string text)

em(string text)

codespan(string code)

br()

del(string text)

link(string href, string title, string text)

image(string href, string title, string text)

gfm

boolean类型 - 默认为true

tables

boolean类型 - 默认为true

开启GFM tables。这个选项要求gfm选项被设置为true。

breaks

boolean类型 - 默认为false

开启GFM line breaks。这个选项要求gfm选项被设置为true。

pedantic

boolean类型 - 默认为false

模糊部分尽可能的遵循markdown.pl。不修复原始的markdown中的bug或poor behavior。

sanitize

boolean类型 - 默认为false

输出审查。忽略任何输入的HTML。

smartLists

boolean类型 - 默认为true

Use smarter list behavior than the original markdown. May eventually be default with the old behavior moved into pedantic.

smartypants

boolean类型 - 默认为false

Use "smart" typograhic punctuation for things like quotes and dashes.

4. 访问lexer和parser

如果你愿意,你可以直接访问lexer和parser。

var tokens = marked.lexer(text, options);

console.log(marked.parser(tokens));

var lexer = new marked.Lexer(options);

var tokens = lexer.lex(text);

console.log(tokens);

console.log(lexer.rules);

5. CLI

$ marked -o hello.html

hello world

^D

$ cat hello.html

hello world

6. Philosophy behind marked

The point of marked was to create a markdown compiler where it was possible tofrequently parse huge chunks of markdown without having to worry aboutcaching the compiled output somehow...or blocking for an unnecesarily long time.

marked is very concise and still implements all markdown features. It is alsonow fully compatible with the client-side.

marked more or less passes the official markdown test suite in itsentirety. This is important because a surprising number of markdown compilerscannot pass more than a few tests. It was very difficult to get marked ascompliant as it is. It could have cut corners in several areas for the sakeof performance, but did not in order to be exactly what you expect in termsof a markdown rendering. In fact, this is why marked could be considered at adisadvantage in the benchmarks above.

Along with implementing every markdown feature, marked also implements GFMfeatures.

7. 基准

node v0.8.x

$ node test --bench

marked completed in 3411ms.

marked (gfm) completed in 3727ms.

marked (pedantic) completed in 3201ms.

robotskirt completed in 808ms.

showdown (reuse converter) completed in 11954ms.

showdown (new converter) completed in 17774ms.

markdown-js completed in 17191ms.

Discount是用C语言编写的一个转换器,Marked现在比Discount还要快。

对于那些感到怀疑的:这些基准运行全部的markdown测试组件1000次。测试组件测试每个功能,并没有单独的偏向于某个特定的方面。

Pro level

如果你愿意,你可以直接访问lexer和parser。

var tokens = marked.lexer(text, options);

console.log(marked.parser(tokens));

var lexer = new marked.Lexer(options);

var tokens = lexer.lex(text);

console.log(tokens);

console.log(lexer.rules);

$ node

> require('marked').lexer('> i am using marked.')

[ { type: 'blockquote_start' },

{ type: 'paragraph',

text: 'i am using marked.' },

{ type: 'blockquote_end' },

links: {} ]

8. 运行测试以及贡献

If you want to submit a pull request, make sure your changes pass the test suite. If you're adding a new feature, be sure to add your own test.

The marked test suite is set up slightly strangely: test/new is for all tests that are not part of the original markdown.pl test suite (this is where your test should go if you make one). test/original is only for the original markdown.pl tests. test/tests houses both types of tests after they have been combined and moved/generated by running node test --fix or marked --test --fix.

In other words, if you have a test to add, add it to test/new/ and then regenerate the tests with node test --fix. Commit the result. If your test uses a certain feature, for example, maybe it assumes GFM is not enabled, you can add .nogfm to the filename. So, my-test.text becomes my-test.nogfm.text. You can do this with any marked option. Say you want line breaks and smartypants enabled, your filename should be: my-test.breaks.smartypants.text.

To run the tests:

cd marked/

node test

贡献与许可协议

如果你向该项目贡献代码,则默认你允许在MIT协议下分发你的代码。You are also implicitly verifying that all code is your original work.

9. 许可协议

Copyright (c) 2011-2014, Christopher Jeffrey. (MIT License)

See LICENSE for more info.

marked转换html失败,JavaScript使用marked.js在线Markdown转HTML相关推荐

  1. marked转换html失败,marked-JavaScript中文网-JavaScript教程资源分享门户

    A markdown parser built for speed Marked ⚡ built for speed ⬇️ low-level compiler for parsing markdow ...

  2. JavaScript基础和js概括

    js内容概括: Html 结构化 CSS 样式 JavaScript 行为交互 01.JavaScript基础 02.JavaScript操作BOM对象 03.JavaScript操作DOM对象 ** ...

  3. Javascript开发技巧(JS中的变量、运算符、分支结构、循环结构)

    一.Js简介和入门 继续跟进JS开发的相关教程. <!-- [使用JS的三种方式] 1.HTML标签中内嵌JS(不提倡使用): 示例:<button οnclick="javas ...

  4. JavaScript学习10 JS数据类型、强制类型转换和对象属性

    JavaScript学习10 JS数据类型.强制类型转换和对象属性 JavaScript数据类型 JavaScript中有五种原始数据类型:Undefined.Null.Boolean.Number以 ...

  5. 自学JavaScript第一天- JS 基础

    自学JavaScript第一天- JS 基础 JS 写在哪里 注释 行内 js 内部 js 外部 js JS 基础语法 语句 大小写 代码块 折行 变量 声明 var .let.const 及作用域 ...

  6. 超级实用的javascript经典大全 js大全

    •事件源对象 event.srcElement.tagName event.srcElement.type •捕获释放 event.srcElement.setCapture();  event.sr ...

  7. JavaScript:引用js文件时的编码格式问题

    今天在jsp页面引入js时,网页查看源码js文件老是乱码,弄了半天,终于解决了. 如果js文件的编码格式是utf-8,并且含有中文,那么按照正常的方法引用,就会出现乱码的情况. 方法/步骤 如果js文 ...

  8. 超酷的实时颜色数据跟踪javascript类库 - Tracking.js

    来源:GBin1.com 今天介绍这款超棒的Javascript类库是 - Tracking.js,它能够独立不依赖第三方类库帮助开发人员动态跟踪摄像头输出相关数据. 这些数据包括了颜色或者是人, 这 ...

  9. javascript:jquery.history.js使用方法

    javascript:jquery.history.js使用方法 step1:download jquery.history.js step2:create a test page as follow ...

  10. Angular Component TypeScript代码和最后转换生成的JavaScript代码比较

    TypeScript代码使用@Component定义一个Component: @Component({selector: 'app-shipping',templateUrl: './shipping ...

最新文章

  1. mysql中vlookup函数_wps表中vlookup函数使用方法将一表引到另一表
  2. hdu5643 King's Game(约瑟夫环+线段树)
  3. 创建的二叉树后续非递归遍历结果为_一入递归深似海,从此offer是路人
  4. PAT 1012 数字分类 (20 分)(C语言)
  5. 1010 一元多项式求导 (25 分)—PAT (Basic Level) Practice (中文)
  6. python处理pdf文件_python处理操作pdf全攻略
  7. linux下blast设计引物,手把手教你设计引物(图文并茂)
  8. Facebook广告收费出价方式之cpi
  9. Flixel横板游戏制作教程(九)—SquashingthePlayer(挤压Player)
  10. linux+记账软件下载,快速记账软件下载-快速记账appv3.11.0-Linux公社
  11. 什么是史诗、特性、用户故事和任务
  12. 火柴人生存挑战2html5游戏在线玩,火柴人生存挑战
  13. 网页小图标和文字混排时如何对齐基准线
  14. 赛车游戏中赛车的物理建模
  15. st7920驱动OCMJ2X8C屏使用CGRAM自定义图标
  16. windows下nginx配置OpenSSL自签名证书
  17. shell脚本-eval的用法
  18. Pygame开发Flappy Bird小游戏(上)
  19. 传统开发有必要学Dubbo吗
  20. 第三章 模型篇:模型与模型的搭建

热门文章

  1. Pythonic的Python向量夹角余弦值计算
  2. 2016 安全行业全景图——By 安全牛
  3. layui 显示饼图_echarts实现饼图绘制
  4. 无法使用安全密码身份验证登录到服务器,使用安全密码验证登录(SPA)”后为什么登录失败...
  5. MySQL系列之STRAIGHT JOIN用法简介
  6. SCI投稿如何选择目标期刊
  7. Diskpart 删除OEM分区方法,set id=07 override 无效处理方法
  8. bzoj 2144: 跳跳棋
  9. 绕过AppLocker系列之MSIEXEC的利用
  10. JBOD(jbod和raid0)