Last change
on this file since 571e0df was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago |
initial commit
|
-
Property mode
set to
100644
|
File size:
1.0 KB
|
Line | |
---|
1 | var punycode = require('punycode');
|
---|
2 | var revEntities = require('./reversed.json');
|
---|
3 |
|
---|
4 | module.exports = encode;
|
---|
5 |
|
---|
6 | function encode (str, opts) {
|
---|
7 | if (typeof str !== 'string') {
|
---|
8 | throw new TypeError('Expected a String');
|
---|
9 | }
|
---|
10 | if (!opts) opts = {};
|
---|
11 |
|
---|
12 | var numeric = true;
|
---|
13 | if (opts.named) numeric = false;
|
---|
14 | if (opts.numeric !== undefined) numeric = opts.numeric;
|
---|
15 |
|
---|
16 | var special = opts.special || {
|
---|
17 | '"': true, "'": true,
|
---|
18 | '<': true, '>': true,
|
---|
19 | '&': true
|
---|
20 | };
|
---|
21 |
|
---|
22 | var codePoints = punycode.ucs2.decode(str);
|
---|
23 | var chars = [];
|
---|
24 | for (var i = 0; i < codePoints.length; i++) {
|
---|
25 | var cc = codePoints[i];
|
---|
26 | var c = punycode.ucs2.encode([ cc ]);
|
---|
27 | var e = revEntities[cc];
|
---|
28 | if (e && (cc >= 127 || special[c]) && !numeric) {
|
---|
29 | chars.push('&' + (/;$/.test(e) ? e : e + ';'));
|
---|
30 | }
|
---|
31 | else if (cc < 32 || cc >= 127 || special[c]) {
|
---|
32 | chars.push('&#' + cc + ';');
|
---|
33 | }
|
---|
34 | else {
|
---|
35 | chars.push(c);
|
---|
36 | }
|
---|
37 | }
|
---|
38 | return chars.join('');
|
---|
39 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.