var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.
The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).
var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.
The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).
Note that if you still want to exclude a set, including things like slashes and special characters you can do the following:
var outString = sourceString.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, '');
take special note that in order to also include the "minus" character, you need to escape it with a backslash like the latter group. if you don't it will also select 0-9 which is probably undesired.
Efficient way of replacing special characters - JavaScript - SitePoint Forums | Web Development & Design Community
ascii - How to replace all special characters using javascript - Stack Overflow
string - How to replace special characters in JavaScript - Stack Overflow
Find and replace all special characters in all json keys
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"
Although deprecated, the escape('myString'); method will do the job and cater for both ? and ! symbols