index.js 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*!
  2. * preserve <https://github.com/jonschlinkert/preserve>
  3. *
  4. * Copyright (c) 2014-2015, Jon Schlinkert.
  5. * Licensed under the MIT license.
  6. */
  7. 'use strict';
  8. /**
  9. * Replace tokens in `str` with a temporary, heuristic placeholder.
  10. *
  11. * ```js
  12. * tokens.before('{a\\,b}');
  13. * //=> '{__ID1__}'
  14. * ```
  15. *
  16. * @param {String} `str`
  17. * @return {String} String with placeholders.
  18. * @api public
  19. */
  20. exports.before = function before(str, re) {
  21. return str.replace(re, function (match) {
  22. var id = randomize();
  23. cache[id] = match;
  24. return '__ID' + id + '__';
  25. });
  26. };
  27. /**
  28. * Replace placeholders in `str` with original tokens.
  29. *
  30. * ```js
  31. * tokens.after('{__ID1__}');
  32. * //=> '{a\\,b}'
  33. * ```
  34. *
  35. * @param {String} `str` String with placeholders
  36. * @return {String} `str` String with original tokens.
  37. * @api public
  38. */
  39. exports.after = function after(str) {
  40. return str.replace(/__ID(.{5})__/g, function (_, id) {
  41. return cache[id];
  42. });
  43. };
  44. function randomize() {
  45. return Math.random().toString().slice(2, 7);
  46. }
  47. var cache = {};