Delphi编解码JS字符串

Delphi编解码JS字符串.- DelphiGear.cn

今天在CSDN回答网友问题,实际上就是JS字符串的解码.给他写了几行简单的代码,转义符也没全部处理.
闲着没事手痒痒,就把JS字符串的编解码都写出来,转义符也全部处理了.说不定以后用得上.
参考的Json.org上的编码规范.

CSDN问题

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
64
65
66
67
68
69
70
71
72
73
74
function EncodeJSStr(const value: Widestring): Widestring;
var
  P: PWideChar;
begin
  Result := '';
  P := PChar(value);
  while P^ <> #0 do
  begin
    case P^ of
      '"', '\', '/':
        Result := Result + '\' + P^;
      #$08:
        Result := Result + '\b';
      #$0C:
        Result := Result + '\f';
      #$0A:
        Result := Result + '\n';
      #$0D:
        Result := Result + '\r';
      #$09:
        Result := Result + '\t';
    else
      if WORD(P^) > $FF then
        Result := Result + LowerCase(Format('\u%x', [WORD(P^)]))
      else
        Result := Result + P^;
    end;
    inc(P);
  end;
end;
 
function DecodeJSStr(const value: Widestring): Widestring;
var
  P: PWideChar;
  v: WideChar;
  tmp: Widestring;
begin
  Result := '';
  P := PChar(value);
  while P^ <> #0 do
  begin
    v := #0;
    case P^ of
      '\':
        begin
          inc(P);
          case P^ of
            '"', '\', '/':
              v := P^;
            'b':
              v := #$08;
            'f':
              v := #$0C;
            'n':
              v := #$0A;
            'r':
              v := #$0D;
            't':
              v := #$09;
            'u':
              begin
                tmp := Copy(P, 2, 4);
                v := WideChar(StrToInt(' + tmp));
                inc(P, 4);
              end;
          end;
        end;
    else
      v := P^;
    end;
    Result := Result + v;
    inc(P);
  end;
end;