delphi编解码JS字符串  
官方Delphi 学习QQ群: 682628230(三千人)\n
频道

delphi编解码JS字符串


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

function EncodeJSStr(const value: Widestring): Widestring;
var
  P: PWideChar;
begin
  Result := '';
  P := PWideChar(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 := PWideChar(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;

推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 DelphiW.com 开发 源码 文档 技巧 All Rights Reserved
晋ICP备14006235号-8 晋公网安备 14108102000087号

执行时间: 0.042152166366577 seconds