0

I'm looking for a way to remove these characters from a string in javascript (and spaces).

?[]/\=<>:;,'\"&$#*()|~`!{}

I am unsure how to construct this:

"mystring is - ?[] hello ".replace(regex, "");

Some elements need escaping, some do not?

bradley
  • 776
  • 2
  • 11
  • 29

1 Answers1

1

Inside a character class [], most don't need escaping:

var pattern = /[?\[\]/\\=<>:;,'"&$#*()|~`!{}]/g;
"mystring is - ?[] hello ".replace(pattern, "");

The g flag is added for global replacement.

alert("mystring is -<> ;:,'\"&%^=!{} ?[] hello ".replace(pattern, ""));

// Prints:
mystring is - %^ hello

Here it is in action

Michael Berkowski
  • 267,341
  • 46
  • 444
  • 390