0

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 Answers1

0

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

Community
  • 1
  • 1
Ryan Rentfro
  • 1,642
  • 3
  • 16
  • 18