Skip to content

Commit

Permalink
+ escapeHTML(str, all)
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudcome committed Jan 18, 2017
1 parent 9a738e4 commit ac94dea
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "blear.utils.string",
"version": "1.0.8",
"version": "1.0.9",
"description": "string utils",
"scripts": {
"live": "browser-sync start --config bs-config.js",
Expand Down
29 changes: 21 additions & 8 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,20 +156,33 @@ exports.padEnd = function (str, maxLength, char) {
};




/**
* 编码字符串为 html 实体符
* @param str
* @param [all] {boolean} 是否编码所有字符
* @returns {string|string}
*/
exports.escapeHTML = function (str) {
exports.escapeHTML = function (str, all) {
str = str + '';
object.each(escapeHTMLMap, function (src, reg) {
str = str.replace(reg, src);
});

return str;
if (!all) {
object.each(escapeHTMLMap, function (src, reg) {
str = str.replace(reg, src);
});

return str;
}

var ret = '';
var start = 0;
var length = str.length;

for (; start < length; start++) {
var chr = str.charCodeAt(start);
ret += '&#' + chr + ';'
}

return ret;
};


Expand All @@ -186,7 +199,7 @@ exports.unescapeHTML = function (str) {
object.each(unescapeHTMLMap, function (to, reg) {
str = str.replace(reg, to);
});

return str;
};

Expand Down
6 changes: 6 additions & 0 deletions test/test.index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,14 @@ describe('测试文件', function () {
it('.escapeHTML/.unescapeHTML', function () {
var str1 = '<&>"\'/';
var str2 = '&lt;&amp;&gt;&quot;&apos;&#x2f;';
var str3 = '123';

expect(string.escapeHTML(str1)).toEqual(str2);
expect(string.unescapeHTML(str2)).toEqual(str1);
var ret = string.escapeHTML(str3, true);
var divEl = document.createElement('div');
divEl.innerHTML = ret;
expect(divEl.innerHTML).toBe(str3);
});

it('.escapeRegExp', function () {
Expand Down

0 comments on commit ac94dea

Please sign in to comment.