Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace all special characters using javascript

I want to replace all special character in ASCII-%. Like this list:

? -> %3F
! -> %21
...

Till now i have replaced 2 special characters. But i doesnt know a simple method to replace all special characters.

This is my code:

var replacer1 = new RegExp("\\?", "g");
var replacer2 = new RegExp("/", "g");
var q = ((query).replace(replacer1, "%3F")).replace(replacer2, "%2F");
like image 576
R2D2 Avatar asked Sep 05 '26 14:09

R2D2


1 Answers

Looks like what your trying to do is url encode your special characters just use the functions:

  • encodeURIComponent
  • encodeURI

depending on whether you are encoding an entire url or just a component. e.g.

encodeURIComponent("as686sa8d6sa8787^%^%$^£$%£$%");
//Output: "as686sa8d6sa8787%5E%25%5E%25%24%5E%C2%A3%24%25%C2%A3%24%25"
like image 56
ShaneQful Avatar answered Sep 07 '26 04:09

ShaneQful



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!