I am trying to create a regex that always removes the following characters in a string:
\ /: *? " < > |
I have a string like the following:
const str = 't""h<i"|s< i/??||/s::>: **a? t:|:e>>s\\t*///';
When I use replace()
like the following:
const sanitize = str.replace(/\*|:|\/|"|\?|\\|<|>|\|/g,'');
I get the following:
"this is a test"
This is the desired result. The only time this doesn't work is if there is a single backslash \
in front of the first letter of a word -- it will then also remove the first letter of that word. Example:
const str = 't\his is a \test';
const sanitize = str.replace(/\*|:|\/|"|\?|\\|<|>|\|/g,'');
Will result in:
"this is a est"
How do I remove all backslashes \
without also removing a whitelisted character that happens to be next to the removed blackslash?
You should use String.raw
to make it so the single backslashes are escaped into double backslashes:
const str = String.raw`t\his is a \test`; const sanitize = str.replace(/\*|:|\/|"|\?|\\|<|>|\|/g,''); console.log(sanitize);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.