红酒泡绿茶 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 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题