333
schangxiang@126.com
2025-09-19 18966e02fb573c7e2bb0c6426ed792b38b910940
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
'use strict';
 
/**
 * Escape JavaScript to \xHH format
 */
 
// escape \x00-\x7f
// except 0-9,A-Z,a-z(\x2f-\x3a \x40-\x5b \x60-\x7b)
 
// eslint-disable-next-line
const MATCH_VULNERABLE_REGEXP = /[\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]/;
// eslint-enable-next-line
 
const BASIC_ALPHABETS = new Set('abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''));
 
const map = {
  '\t': '\\t',
  '\n': '\\n',
  '\r': '\\r',
};
 
function escapeJavaScript(string) {
 
  const str = '' + string;
  const match = MATCH_VULNERABLE_REGEXP.exec(str);
 
  if (!match) {
    return str;
  }
 
  let res = '';
  let index = 0;
  let lastIndex = 0;
  let ascii;
 
  for (index = match.index; index < str.length; index++) {
    ascii = str[index];
    if (BASIC_ALPHABETS.has(ascii)) {
      continue;
    } else {
      if (map[ascii] === undefined) {
        const code = ascii.charCodeAt(0);
        if (code > 127) {
          continue;
        } else {
          map[ascii] = '\\x' + code.toString(16);
        }
      }
    }
 
    if (lastIndex !== index) {
      res += str.substring(lastIndex, index);
    }
 
    lastIndex = index + 1;
    res += map[ascii];
  }
 
  return lastIndex !== index ? res + str.substring(lastIndex, index) : res;
 
}
 
module.exports = escapeJavaScript;