0
var unicode = ['!', '@', '%', '$', '#', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '}', '[', ']', '\\', '|', ':', ';', '\'', '"', ',', '<', '>', '.', '/', '?', '~', '`'];
var removeunicode = "my message!!@!(@^!@&(*";
for (var i = 0; i < unicode.length; i++) {
    removeunicode = removeunicode.replace(new RegExp(unicode[i], 'g'), "");
}

No idea what's the problem here, looks perfectly fine, basically its stripping all the unicode off the message I put, and RegExp seems to be messing around with me giving me

SyntaxError: Invalid regular expression: /*/: Nothing to repeat

can anybody help me? :)

Tushar
  • 85,780
  • 21
  • 159
  • 179

1 Answers1

0

You need to escape those special characters, but you can write it like

if (!RegExp.escape) {
  RegExp.escape = function(value) {
    return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
  };
}


var unicode = ['!', '@', '%', '$', '#', '^', '&', '*', '(', ')', '-', '_', '+', '=', '{', '}', '[', ']', '\\', '|', ':', ';', '\'', '"', ',', '<', '>', '.', '/', '?', '~', '`'];
var removeunicode = "my message!!@!(@^!@&(*";

var regex = new RegExp(unicode.map(function(val) {
  return RegExp.escape(val);
}).join('|'), 'g');
removeunicode = removeunicode.replace(regex, "");
snippet.log(removeunicode);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531