aboutsummaryrefslogtreecommitdiff
path: root/js/lib/common.js
blob: c365e534ab125e6acdbae7f95ba40d34991950cf (plain)
  1. "use strict";
  2. var entityToChar = require('./html5-entities.js').entityToChar;
  3. var ENTITY = "&(?:#x[a-f0-9]{1,8}|#[0-9]{1,8}|[a-z][a-z0-9]{1,31});";
  4. var reBackslashOrAmp = /[\\&]/;
  5. var ESCAPABLE = '[!"#$%&\'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]';
  6. var reEntityOrEscapedChar = new RegExp('\\\\' + ESCAPABLE + '|' + ENTITY, 'gi');
  7. var XMLSPECIAL = '[&<>"]';
  8. var reXmlSpecial = new RegExp(XMLSPECIAL, 'g');
  9. var reXmlSpecialOrEntity = new RegExp(ENTITY + '|' + XMLSPECIAL, 'gi');
  10. var unescapeChar = function(s) {
  11. if (s[0] === '\\') {
  12. return s[1];
  13. } else {
  14. return entityToChar(s);
  15. }
  16. };
  17. // Replace entities and backslash escapes with literal characters.
  18. var unescapeString = function(s) {
  19. if (reBackslashOrAmp.test(s)) {
  20. return s.replace(reEntityOrEscapedChar, unescapeChar);
  21. } else {
  22. return s;
  23. }
  24. };
  25. var normalizeURI = function(uri) {
  26. try {
  27. return encodeURI(decodeURI(uri));
  28. }
  29. catch(err) {
  30. return uri;
  31. }
  32. };
  33. var replaceUnsafeChar = function(s) {
  34. switch (s) {
  35. case '&':
  36. return '&amp;';
  37. case '<':
  38. return '&lt;';
  39. case '>':
  40. return '&gt;';
  41. case '"':
  42. return '&quot;';
  43. default:
  44. return s;
  45. }
  46. };
  47. var escapeXml = function(s, preserve_entities) {
  48. if (reXmlSpecial.test(s)) {
  49. if (preserve_entities) {
  50. return s.replace(reXmlSpecialOrEntity, replaceUnsafeChar);
  51. } else {
  52. return s.replace(reXmlSpecial, replaceUnsafeChar);
  53. }
  54. } else {
  55. return s;
  56. }
  57. };
  58. module.exports = { unescapeString: unescapeString,
  59. normalizeURI: normalizeURI,
  60. escapeXml: escapeXml
  61. };