红酒泡绿茶 2016-09-17 23:50
浏览 123

如何编码和解码javascript或jquery中的所有特殊字符?

I want to be able to encode and decode all the following characters using javascript or jquery...

~!@#$%^&*()_+|}{:"?><,./';[]\=-`

I tried to encode them using this...

var cT = encodeURI(oM); // oM holds the special characters
cT = cT.replace(/[!"#$%&'()*+,.\/:;<=>?@[\\\]^`{|}~]/g, "\\\\$&");

Which does encode them, or escape them rather, but then I am trying to do the reverse with this...

decodeURIComponent(data.convo.replace(/\+/g, ' '));

But, it's not coming out in any way desired.

I've built a chat plugin for jquery, but the script crashes if someone enters a special character. I want the special characters to get encoded, then when they get pulled out of the data base, they should be decoded. I tried using urldecode in PHP before the data is returned to the ajax request but it's coming out horribly wrong.

I would think that there exists some function to encode and decode all special characters.

Oh, one caveat for this is that I'm wrapping each message with html elements, so I think the decoding needs to be done server side, before the message is wrapped, or be able to know when to ignore valid html tags and decode the other characters that are just what the user wanted to type.

Am I encoding/escaping them wrong to begin with?

Is that why the results are horrible?

  • 写回答

1条回答 默认 最新

  • duankeng9477 2016-09-17 23:56
    关注

    This is pretty simple in javascript

    //Note that i have escaped the " in the string - this means it still gets processed
    var exampleInput = "Hello there h4x0r ~!@#$%^&*()_+|}{:\"?><,./';[]\=-`";
    var encodedInput = encodeURI(exampleInput);
    var decodedInput = decodeURI(encodedInput);
    console.log(exampleInput);
    console.log(encodedInput);
    console.log(decodedInput);
    

    Just encode and decode the input. If something else is breaking in your script it means you are not stripping away things that you are somehow processing. It's hard to provide an accurate answer as you can see encoding and decoding the URI standards does not crash things. Only the processing of this content improperly would cause issues.

    When you output the content in HTML you should be encoding the HTML entities.

    Reference this thread Encode html entities in javascript if you need to actually encode for display inside HTML safely.

    An additional reference on how html entities work can be found here: W3 Schools - HTML Entities and W3 Schools - HTML Symbols

    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料