opusdev/vector-similarity-api
1
1/*!2 * escape-html3 * Copyright(c) 2012-2013 TJ Holowaychuk4 * Copyright(c) 2015 Andreas Lubbe5 * Copyright(c) 2015 Tiancheng "Timothy" Gu6 * MIT Licensed7 */8 9'use strict';10 11/**12 * Module variables.13 * @private14 */15 16var matchHtmlRegExp = /["'&<>]/;17 18/**19 * Module exports.20 * @public21 */22 23module.exports = escapeHtml;24 25/**26 * Escape special characters in the given string of html.27 *28 * @param {string} string The string to escape for inserting into HTML29 * @return {string}30 * @public31 */32 33function escapeHtml(string) {34 var str = '' + string;35 var match = matchHtmlRegExp.exec(str);36 37 if (!match) {38 return str;39 }40 41 var escape;42 var html = '';43 var index = 0;44 var lastIndex = 0;45 46 for (index = match.index; index < str.length; index++) {47 switch (str.charCodeAt(index)) {48 case 34: // "49 escape = '"';50 break;51 case 38: // &52 escape = '&';53 break;54 case 39: // '55 escape = ''';56 break;57 case 60: // <58 escape = '<';59 break;60 case 62: // >61 escape = '>';62 break;63 default:64 continue;65 }66 67 if (lastIndex !== index) {68 html += str.substring(lastIndex, index);69 }70 71 lastIndex = index + 1;72 html += escape;73 }74 75 return lastIndex !== index76 ? html + str.substring(lastIndex, index)77 : html;78}79 