aboutsummaryrefslogtreecommitdiff
path: root/js/lib/common.js
blob: 6481c68a94386296676f0499f7b8aee7baaa2d3a (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. return encodeURI(decodeURI(uri));
  27. };
  28. var replaceUnsafeChar = function(s) {
  29. switch (s) {
  30. case '&':
  31. return '&amp;';
  32. case '<':
  33. return '&lt;';
  34. case '>':
  35. return '&gt;';
  36. case '"':
  37. return '&quot;';
  38. default:
  39. return s;
  40. }
  41. };
  42. var escapeXml = function(s, preserve_entities) {
  43. if (reXmlSpecial.test(s)) {
  44. if (preserve_entities) {
  45. return s.replace(reXmlSpecialOrEntity, replaceUnsafeChar);
  46. } else {
  47. return s.replace(reXmlSpecial, replaceUnsafeChar);
  48. }
  49. } else {
  50. return s;
  51. }
  52. };
  53. module.exports = { unescapeString: unescapeString,
  54. normalizeURI: normalizeURI,
  55. escapeXml: escapeXml
  56. };