Creating javascript regex tp replace characters using whitelist -


i'm trying create regex replace characters not in specified white list (letters,digits,whitespaces, brackets, question mark , explanation mark)
code :

var regex = /^[^(\s|\w|\d|()|?|!|<br>)]*?$/;     qstr += tempstr.replace(regex, ''); 

what wrong ?

thank you

  • the anchors wrong - allow regex match entire string
  • the lazy quantifier wrong - wouldn't want regex match 0 characters (if have removed anchors)
  • the parentheses , pipe characters wrong - don't need them in character class.
  • the <br> wrong - can't match specific substrings in character class.
  • the \d superfluous since it's contained in \w (thanks alex k.!)
  • you're missing global modifier make sure can more 1 replace.
  • you should using + instead of * in order not replace lots of empty strings themselves.

try

var regex = /[^\s\w()?!]+/g; 

and handle <br>s independently (before regex applied, or brackets removed).


Comments

Popular posts from this blog

c++ - Creating new partition disk winapi -

Android Prevent Bluetooth Pairing Dialog -

VBA function to include CDATA -