Code Monkey home page Code Monkey logo

js-xss's Introduction

NPM version Node.js CI Test coverage David deps node version npm download npm license

Sanitize untrusted HTML (to prevent XSS) with a configuration specified by a Whitelist.

Greenkeeper badge

xss


xss is a module used to filter input from users to prevent XSS attacks. (What is XSS attack?)

Project Homepage: http://jsxss.com

Try Online: http://jsxss.com/en/try.html

中文版文档


Features

  • Specifies HTML tags and their attributes allowed with whitelist
  • Handle any tags or attributes using custom function.

Reference

Benchmark (for references only)

For test code please refer to benchmark directory.

They are using xss module

Install

NPM

npm install xss

Bower

bower install xss

Or

bower install https://github.com/leizongmin/js-xss.git

Usages

On Node.js

var xss = require("xss");
var html = xss('<script>alert("xss");</script>');
console.log(html);

On Browser

Shim mode (reference file test/test.html):

<script src="https://rawgit.com/leizongmin/js-xss/master/dist/xss.js"></script>
<script>
  // apply function filterXSS in the same way
  var html = filterXSS('<script>alert("xss");</scr' + "ipt>");
  alert(html);
</script>

AMD mode - shim:

<script>
  require.config({
    baseUrl: "./",
    paths: {
      xss: "https://rawgit.com/leizongmin/js-xss/master/dist/xss.js",
    },
    shim: {
      xss: { exports: "filterXSS" },
    },
  });
  require(["xss"], function (xss) {
    var html = xss('<script>alert("xss");</scr' + "ipt>");
    alert(html);
  });
</script>

Notes: please don't use the URL https://rawgit.com/leizongmin/js-xss/master/dist/xss.js in production environment.

Command Line Tool

Process File

You can use the xss command line tool to process a file. Usage:

xss -i <input_file> -o <output_file>

Example:

xss -i origin.html -o target.html

Active Test

Run the following command, them you can type HTML code in the command-line, and check the filtered output:

xss -t

For more details, please run $ xss -h to see it.

Custom filter rules

When using the xss() function, the second parameter could be used to specify custom rules:

options = {}; // Custom rules
html = xss('<script>alert("xss");</script>', options);

To avoid passing options every time, you can also do it in a faster way by creating a FilterXSS instance:

options = {}; // Custom rules
myxss = new xss.FilterXSS(options);
// then apply myxss.process()
html = myxss.process('<script>alert("xss");</script>');

Details of parameters in options would be described below.

Whitelist

By specifying a whiteList, e.g. { 'tagName': [ 'attr-1', 'attr-2' ] }. Tags and attributes not in the whitelist would be filter out. For example:

// only tag a and its attributes href, title, target are allowed
var options = {
  whiteList: {
    a: ["href", "title", "target"],
  },
};
// With the configuration specified above, the following HTML:
// <a href="#" onclick="hello()"><i>Hello</i></a>
// would become:
// <a href="#">&lt;i&gt;Hello&lt;/i&gt;</a>

For the default whitelist, please refer xss.whiteList.

allowList is also supported, and has the same function as whiteList.

Customize the handler function for matched tags

By specifying the handler function with onTag:

function onTag(tag, html, options) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // html is the HTML of this tag, e.g. '<a>' for tag <a>
  // options is some addition informations:
  //   isWhite    boolean, whether the tag is in whitelist
  //   isClosing  boolean, whether the tag is a closing tag, e.g. true for </a>
  //   position        integer, the position of the tag in output result
  //   sourcePosition  integer, the position of the tag in input HTML source
  // If a string is returned, the current tag would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter attributes using onTagAttr, as described below
  //   If not in whitelist: handle by onIgnoreTag, as described below
}

Customize the handler function for attributes of matched tags

By specifying the handler function with onTagAttr:

function onTagAttr(tag, name, value, isWhiteAttr) {
  // tag is the name of current tag, e.g. 'a' for tag <a>
  // name is the name of current attribute, e.g. 'href' for href="#"
  // isWhiteAttr whether the attribute is in whitelist
  // If a string is returned, the attribute would be replaced with the string
  // If return nothing, the default measure would be taken:
  //   If in whitelist: filter the value using safeAttrValue as described below
  //   If not in whitelist: handle by onIgnoreTagAttr, as described below
}

Customize the handler function for tags not in the whitelist

By specifying the handler function with onIgnoreTag:

function onIgnoreTag(tag, html, options) {
  // Parameters are the same with onTag
  // If a string is returned, the tag would be replaced with the string
  // If return nothing, the default measure would be taken (specifies using
  // escape, as described below)
}

Customize the handler function for attributes not in the whitelist

By specifying the handler function with onIgnoreTagAttr:

function onIgnoreTagAttr(tag, name, value, isWhiteAttr) {
  // Parameters are the same with onTagAttr
  // If a string is returned, the value would be replaced with this string
  // If return nothing, then keep default (remove the attribute)
}

Customize escaping function for HTML

By specifying the handler function with escapeHtml. Following is the default function (Modification is not recommended):

function escapeHtml(html) {
  return html.replace(/</g, "&lt;").replace(/>/g, "&gt;");
}

Customize escaping function for value of attributes

By specifying the handler function with safeAttrValue:

function safeAttrValue(tag, name, value) {
  // Parameters are the same with onTagAttr (without options)
  // Return the value as a string
}

Customize output attribute value syntax for HTML

By specifying a singleQuotedAttributeValue. Use true for '. Otherwise default " will be used

var options = {
  singleQuotedAttributeValue: true,
};
// With the configuration specified above, the following HTML:
// <a href="#">Hello</a>
// would become:
// <a href='#'>Hello</a>

Customize CSS filter

If you allow the attribute style, the value will be processed by cssfilter module. The cssfilter module includes a default css whitelist. You can specify the options for cssfilter module like this:

myxss = new xss.FilterXSS({
  css: {
    whiteList: {
      position: /^fixed|relative$/,
      top: true,
      left: true,
    },
  },
});
html = myxss.process('<script>alert("xss");</script>');

If you don't want to filter out the style content, just specify false to the css option:

myxss = new xss.FilterXSS({
  css: false,
});

For more help, please see https://github.com/leizongmin/js-css-filter

Quick Start

Filter out tags not in the whitelist

By using stripIgnoreTag parameter:

  • true filter out tags not in the whitelist
  • false: by default: escape the tag using configured escape function

Example:

If stripIgnoreTag = true is set, the following code:

code:
<script>
  alert(/xss/);
</script>

would output filtered:

code:alert(/xss/);

Filter out tags and tag bodies not in the whitelist

By using stripIgnoreTagBody parameter:

  • false|null|undefined by default: do nothing
  • '*'|true: filter out all tags not in the whitelist
  • ['tag1', 'tag2']: filter out only specified tags not in the whitelist

Example:

If stripIgnoreTagBody = ['script'] is set, the following code:

code:
<script>
  alert(/xss/);
</script>

would output filtered:

code:

Filter out HTML comments

By using allowCommentTag parameter:

  • true: do nothing
  • false by default: filter out HTML comments

Example:

If allowCommentTag = false is set, the following code:

code:<!-- something -->
END

would output filtered:

code: END

Examples

Allow attributes of whitelist tags start with data-

var source = '<div a="1" b="2" data-a="3" data-b="4">hello</div>';
var html = xss(source, {
  onIgnoreTagAttr: function (tag, name, value, isWhiteAttr) {
    if (name.substr(0, 5) === "data-") {
      // escape its value using built-in escapeAttrValue function
      return name + '="' + xss.escapeAttrValue(value) + '"';
    }
  },
});

console.log("%s\nconvert to:\n%s", source, html);

Result:

<div a="1" b="2" data-a="3" data-b="4">hello</div>
convert to:
<div data-a="3" data-b="4">hello</div>

Allow tags start with x-

var source = "<x><x-1>he<x-2 checked></x-2>wwww</x-1><a>";
var html = xss(source, {
  onIgnoreTag: function (tag, html, options) {
    if (tag.substr(0, 2) === "x-") {
      // do not filter its attributes
      return html;
    }
  },
});

console.log("%s\nconvert to:\n%s", source, html);

Result:

<x
  ><x-1>he<x-2 checked></x-2>wwww</x-1
  ><a>
    convert to: &lt;x&gt;<x-1>he<x-2 checked></x-2>wwww</x-1><a></a></a
></x>

Parse images in HTML

var source =
  '<img src="img1">a<img src="img2">b<img src="img3">c<img src="img4">d';
var list = [];
var html = xss(source, {
  onTagAttr: function (tag, name, value, isWhiteAttr) {
    if (tag === "img" && name === "src") {
      // Use the built-in friendlyAttrValue function to escape attribute
      // values. It supports converting entity tags such as &lt; to printable
      // characters such as <
      list.push(xss.friendlyAttrValue(value));
    }
    // Return nothing, means keep the default handling measure
  },
});

console.log("image list:\n%s", list.join(", "));

Result:

image list: img1, img2, img3, img4

Filter out HTML tags (keeps only plain text)

var source = "<strong>hello</strong><script>alert(/xss/);</script>end";
var html = xss(source, {
  whiteList: {}, // empty, means filter out all tags
  stripIgnoreTag: true, // filter out all HTML not in the whitelist
  stripIgnoreTagBody: ["script"], // the script tag is a special case, we need
  // to filter out its content
});

console.log("text: %s", html);

Result:

text: helloend

License

Copyright (c) 2012-2018 Zongmin Lei(雷宗民) <[email protected]>
http://ucdok.com

The MIT License

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

js-xss's People

Contributors

aprilandjan avatar asapien avatar blackglory avatar chengbapi avatar chrizza87 avatar danvk avatar daraz999 avatar davidpett avatar greenkeeper[bot] avatar greenkeeperio-bot avatar island205 avatar jcfranco avatar jim4node avatar leizongmin avatar lumburr avatar maosmurf avatar marekdedic avatar pengvc avatar pgilad avatar ristinolla avatar sbertrang avatar schu34 avatar shigma avatar sijanec avatar slawiko avatar spacegaier avatar timgates42 avatar tomanthony avatar williamstein avatar xingrz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-xss's Issues

Is xss(content) safe to be used in attributes?

It appears this module targets HTML input/output, I should always do

xss('<a href="' + url +'">')

instead of

<a href="xss(url)">link<a/>

right?

This also means I should always do json data -> template render -> xss filter -> append, instead of json data -> xss filter -> template render -> append right?

文档缺少 CSS 配置的说明

非常感谢能提供如此方便的工具,不过在使用的过程中遇到了一个问题:
我写了允许 <p> 标签上有 style 属性,但是结果是 style 属性里的 line-height 属性被过滤掉了。

看了下代码,我看到里面 css 的 xss 过滤用的是另外一个库叫 cssfilter,里面提供了配置 css 属性白名单的功能,但是在说明文档里面没有提到。

为了以后的人能少踩一个坑,建议能加上一点关于 css 的 xss 配置说明。

Filter iframe tags based on their src origin

My use case is:

  1. Allow iframe tags (and white listed attrs) if src is from youtube
  2. Otherwise filter out the tag entirely

I can't find out how to achieve this using current callbacks. Seems you can either accept the tag or not.

v0.1新特性

  • 增加选项用于指定是否过滤不合法的标签:1-过滤不合法的标签 | 2-将不合法的标签转义 | 3-指定函数来处理,默认为1
  • 过滤 href 属性值采用白名单机制:1-允许http和https协议 | 2-指定支持的协议列表 | 3-指定函数来处理,默认为1
  • 所有属性值都应该可以具体指定:标签名-属性名=>处理函数

img src onerror xss 问题

你的这个 repo xss(imgSrc) 时,imgSrc 里面的这种代码https://a"onerror=alert('hello')> 要怎么过滤啊?

命令列使用時,設定檔無效

➜ cat test
<strong>hello</strong><script>alert(/xss/);</script>end
➜ cat config.js
var options = {
  whiteList: [],
  stripIgnoreTag: true
};
➜ xss -i test -c config.js
<strong>hello</strong>&lt;script&gt;alert(/xss/);&lt;/script&gt;end

不知道是否是我哪邊弄錯了?

Problem whitelisting CSS

Hi,

I was reading https://www.npmjs.com/package/xss, and it said if I wanted to allow style tags. I would just need to run the following code

const myxss = new xss.FilterXSS({
  css: false,
});
html = myxss.process(innerText);

However, I can't get it to work. My inner text is

<table>
<thead>
<tr>
<th style="text-align:left"><strong>Left Column</strong></th>
<th style="text-align:right"></th>
</tr>
</thead>
<tbody>
<tr>
<td style="text-align:left"><strong>Left Value</strong></td>
<td style="text-align:right">Right Value</td>
</tr>
</tbody>
</table>

and instead what comes out is

<table>
<thead>
<tr>
<th><strong>Left Column</strong></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Left Value</strong></td>
<td>Right Value</td>
</tr>
</tbody>
</table>

Any guidance would be helpful. Thanks!

td style vertical-align property gets removed

I'm using the filter through js and just found an interesting error. It seems that the filter removes vertical-align property from td styles. Is there a reason for this or just a recommendation to use valign -property?

The code:

filterXSS( content,{
  whiteList: filterList,
  stripIgnoreTag: true,
  stripIgnoreTagBody: ['script']
});

var filterList: {
          ...
          table:  ['width', 'border', 'align', 'valign','style','class'],
          tbody:  ['align', 'valign','style','class'],
          td:     ['width', 'rowspan', 'colspan', 'align', 'valign','style','class'],
          tfoot:  ['align', 'valign','style','class'],
          th:     ['width', 'rowspan', 'colspan', 'align', 'valign','style','class'],
          thead:  ['align', 'valign','style','class'],
          tr:     ['rowspan', 'align', 'valign','style','class']
}

错误的转义

xss > 3 

会被转义成

xss &gt 3

是因为这里
parser.js:102

if (lastPos < html.length) {
    rethtml += escapeHtml(html.substr(lastPos));
  }

没有发现html标签是不应该转义啊

Style attribute on anchor tag throws an exception instead of error

Steps to reproduce:

var options = {
        whiteList: {
          a: ['href', 'id', 'style'],
          em: [],
          span: ['id', 'tabindex'],
          strong: []
        }

and override the onTagAttr, like so:

        onTagAttr: function (tag, name, value, isWhiteAttr) {
            if (isWhiteAttr && xss.safeAttrValue(tag, name, value) === '') {
              grunt.log.error('%s: INVALID VALUE FOR ATTRIBUTE <%s %s="%s">', src, tag, name, value);
              hasErrors += 1;
              errorFound = true;
              return '';
            }
          }

run this over a html file with contents:
<a href='' style='color: #0095dd; text-decoration: none;'>Whatever text</a>

Expected Behaviour:

  1. The xss module logs an error

Actual Behaviour:
Warning: Cannot call method 'process' of undefined Use --force to continue.

@pdehaan

XSS module doesnt sanitize xss vectors in broken html

STR:

Run the xss module on the following contents:

Hesabı təsdiqlə:

Xətalı istək

Səhifə tapılmadı
Cuenta desconocida. <a href="javascript(1)" onclick="javascript:alert('hey')

Desconectado correctamente

La cuenta ya existe. <a href="/signin">Identifícate</a>

Expected Behavior:

  • Error on finding xss vector (javascript) and/or cleaning that up

Actual behavior

  • No errors or cleaning up.

More detailed examples at mozilla/fxa-content-server-l10n#63
@shane-tomlinson

感谢, 使用扩展接口工作正常!

用 老雷 提供的扩展接口,可以很好的实现自定义规则的处理, 我们已经取消了fork, 直接使用最新版本的源码了。 感谢!!

    var customFilter = (function () {
            var xss = new window.filterXSS.FilterXSS({
                safeAttrValue: function (tag, name, value) {
                    // 自定义过滤属性值函数,如果为a标签的href属性,则先判断是否以wiz://开头
                    if (tag === 'a' && name === 'href') {
                        if (value.substr(0, 6) === 'wiz://') {
                            return window.filterXSS.escapeAttrValue(value);
                        }
                    }
                    // 其他情况,使用默认的safeAttrValue处理函数
                    return window.filterXSS.safeAttrValue(tag, name, value);
                }
            });
            return function (html) {
                return xss.process(html);
            };

        })();


   // customFilter(htmlstr);

将safeAttrValue之类的接口暴露出来

有这么一个需求
外站头像链接
将来会放到img标签的src中
但是在让用户填写的时候这个链接只是普通字符串
xss不会处理其中的引号和<>

这样的情况比较复杂, 可能xss无法自动化的处理, 但是可以把相关的方法暴露出来让开发者自己调用

Is js-xss production ready?

Has this package been reviewed by any security firm(s)? I looked through the README but couldn't find any information on the topic. I'm kind of surprised, given that this package has over 1,000 stars, it seems like it is widely used.

I've come across various NPM packages that escape strings, but I'm not sure which is the best to go with. Obviously there is no 100% guarantees in security, but this package seems promising for my use case.

I'd appreciate input from the maintainers or from other package users who are concerned with XSS.

Options object is mutated

var oldKeys = Object.keys(opts);
xss('test', opts);
var newKeys = Object.keys(opts);

oldKeys.length === newKeys.length

Re-using an opts which has stripIgnoreTag defined, will issue a warning:

Notes: cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time

css whitelist doesnt work with spaces

Steps to reproduce

var xss = require('xss');
var options = {
  whiteList: {
    a: ['style']
  },
  css: {
    whiteList: {
      'color': true,
      'text-decoration': true
    }
  }
}
var html = "<a style = 'color: #0095dd; text-decoration: none;'>xss</a>";
var myxss = new xss.FilterXSS(options)
console.log(myxss.process(html))

Expected Behaviour:

The code is valid, and is not sanitized.

Actual behaviour:

The style value is completely removed, even though both color and text-decoration are valid.

If i remove the spaces between style and =, then it works as expected.

win7 无法安装

E:\node work\node-doc-cn-master>npm install xss
npm http GET https://registry.npmjs.org/xss
npm http 304 https://registry.npmjs.org/xss
npm http GET https://registry.npmjs.org/xss/-/xss-0.0.8.tgz
npm http 200 https://registry.npmjs.org/xss/-/xss-0.0.8.tgz
npm ERR! Error: ENOENT, open 'C:\Users\ADMINI~1\AppData\Local\Temp\npm-15224-vgC
KZxTd\1384148008965-0.5113850180059671\package:q'
npm ERR! If you need help, you may report this log at:
npm ERR! http://github.com/isaacs/npm/issues
npm ERR! or email it to:
npm ERR! [email protected]

npm ERR! System Windows_NT 6.1.7601
npm ERR! command "D:\nodist\bin\node.exe" "D:\nodist\bin\node_modules\n
pm\cli.js" "install" "xss"
npm ERR! cwd E:\node work\node-doc-cn-master
npm ERR! node -v v0.10.20
npm ERR! npm -v 1.3.11
npm ERR! path C:\Users\ADMINI~1\AppData\Local\Temp\npm-15224-vgCKZxTd\1384148008
965-0.5113850180059671\package:q
npm ERR! code ENOENT
npm ERR! errno 34
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR! E:\node work\node-doc-cn-master\npm-debug.log
npm ERR! not ok code 0

XSS whiteList issue.

Whenever I use whiteList option all html content is converted into encoded string instead of sample html.

I have used below string:

var source = '<p>Hotel Kadi Palace is located in the <strong>heart </strong>of the <strong>historic center of Florence </strong>'; var html = xss(source, { whiteList: ['href','target'] }); console.log(html);

So I just want to know whether it is functionality or minor bug, and what should I do to get plain html here.

无法过滤 0 宽控制符

如下:

'Cats & Dogs
'.replace(/[\u0000-\u001F]|\u007F/g, '')

把这句贴到 chrome console 里会出现以下报错:

image

原因是在 Dogs 后面,可以用鼠标移动看看,有一个宽度为 0 的不可见字符,用户拷贝了带这样字符的文本,通过表单提交到你的后台,通过 xss() 后没过滤掉,再存到到数据库,最后以 json 变量的形式输出到 html 中,就会因为解析出错而破坏整个 json 结构,从而造成 bug。

这种字符通过 xss 能过滤掉么?

xss attack through style attribute

Hi,

First of all, thank you for this nice library! Your library is the only one I could find that allows filtering on css.

However, I hoped it would filter out xss hacks in css by default, in particular the background: url(javascript:...) hack.

I now have added:

css: {
  onAttr(name, value) {
    if (value.toLowerCase().indexOf('javascript:') != -1) {
      return '';
    }
  },
},

to the options, which I think takes care of this.

I think you should add this filter by default or at least warn that your library doesn't catch this xss issue. Thank you!

cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time

使用以下的opt:

var xssOpt = {
  whiteList:          [],        // 白名单为空,表示过滤所有标签
  stripIgnoreTag:     true,      // 过滤所有非白名单标签的HTML
  stripIgnoreTagBody: ['script'] // script标签较特殊,需要过滤标签中间的内容
};

调用xss(str, xssOpt)的时候,会报下面错误:

Notes: cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time

请问怎么解决。

需要处理标签 <!--comments-->

计划增加新的选项 allowCommentTag 来设置是否允许HTML备注标签:

  • true 表示允许
  • false 表示删除,默认为 false

需要支持IE7

IE7下不支持 str[0] 这种方式读取字符串指定字符,需要更换为 str.charAt(0)

替换前需要测试一下在V8引擎下运行性能是否有影响。

<pre> 里面的 & 会被转义成无效的

<pre><code class="language-html">&lt;body&gt;foo&lt;/body&gt;</code></pre>

会被转义成

<pre><code class="language-html">&amp;lt;body&amp;gt;foo&amp;lt;/body&amp;gt;</code></pre>

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.