escapeUnicode.js 692 B

123456789101112131415161718192021
  1. var toString = require('../lang/toString');
  2. /**
  3. * Escape string into unicode sequences
  4. */
  5. function escapeUnicode(str, shouldEscapePrintable){
  6. str = toString(str);
  7. return str.replace(/[\s\S]/g, function(ch){
  8. // skip printable ASCII chars if we should not escape them
  9. if (!shouldEscapePrintable && (/[\x20-\x7E]/).test(ch)) {
  10. return ch;
  11. }
  12. // we use "000" and slice(-4) for brevity, need to pad zeros,
  13. // unicode escape always have 4 chars after "\u"
  14. return '\\u'+ ('000'+ ch.charCodeAt(0).toString(16)).slice(-4);
  15. });
  16. }
  17. module.exports = escapeUnicode;