属性操作类工具函数

quoteAttributeValueForBrowser对经html转义后的字符串包裹上双引号。

escapeTextContentForBrowser转义["'&<>]类html字符串,且布尔型和数值型都将转化为字符串格式。

quoteAttributeValueForBrowser.js

'use strict';

// 布尔型和数值型转化为字符串后输出;字符串经html转码,逐个字符处理["'&<>]
var escapeTextContentForBrowser = require('./escapeTextContentForBrowser');

// 转码后的字符串外加引号包裹
function quoteAttributeValueForBrowser(value) {
  return '"' + escapeTextContentForBrowser(value) + '"';
}

module.exports = quoteAttributeValueForBrowser;

escapeTextContentForBrowser.js

'use strict';

// 不含["'&<>],跳过转码处理
var matchHtmlRegExp = /["'&<>]/;

// 逐个字符转码字符串
function escapeHtml(string) {
  var str = '' + string;
  var match = matchHtmlRegExp.exec(str);

  if (!match) {
    return str;
  }

  var escape;
  var html = '';
  var index = 0;
  var lastIndex = 0;

  for (index = match.index; index < str.length; index++) {
    switch (str.charCodeAt(index)) {
      case 34:
        // "
        escape = '&quot;';
        break;
      case 38:
        // &
        escape = '&amp;';
        break;
      case 39:
        // '
        escape = '&#x27;'; // modified from escape-html; used to be '&#39'
        break;
      case 60:
        // <
        escape = '&lt;';
        break;
      case 62:
        // >
        escape = '&gt;';
        break;
      default:
        continue;
    }

    if (lastIndex !== index) {
      html += str.substring(lastIndex, index);
    }

    lastIndex = index + 1;
    html += escape;
  }

  return lastIndex !== index ? html + str.substring(lastIndex, index) : html;
}

// 布尔型和数值型转化为字符串后输出;字符串经html转码,逐个字符处理["'&<>]
function escapeTextContentForBrowser(text) {
  if (typeof text === 'boolean' || typeof text === 'number') {
    return '' + text;
  }
  return escapeHtml(text);
}

module.exports = escapeTextContentForBrowser;

猜你喜欢

转载自schifred.iteye.com/blog/2367116