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;

相关阅读 >>

Delphi arp攻击代码

Delphi 回车符 换行符

Delphi实现进制转化(2进制,8进制,10进制,16进制)

Delphi 获取文件crc和md5

Delphi 获取网络文件大小

Delphi adoquery1数据表参数调用

Delphi禁用,启用网卡

Delphi 用代码实现为程序创建快捷方式的二种方法

Delphi 根据数据库结构生成treeview

Delphi任务对话框ttaskdialog类介绍

更多相关阅读请进入《Delphi》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...