-1

As the title above, I want to know how to make these two characters be a pattern in RegExp() function in javascript.
I have tried to put a backlash before it. It works for another special chars, but not for these two.
This is my current pattern :

var disallowed_char=new RegExp("[~!@#$%\^&*()\{\}\\\|\'\"\;\:\.\,\>\<\=\_\+\`\?\/\-]");
// It works

I want char [ and ] be a part of the pattern, so I add these to the pattern :

var disallowed_char=new RegExp("[~!@#$%\^&*()\{\}\\\|\'\"\;\:\.\,\>\<\=\_\+\`\?\/\[\]\-]");
//I put it before - (minus) char, 
//because minus char won't work if placed at the first or in the middle of the pattern
//note : I have tried to put "[" and "]" in other place
//but still doesn't work

Is there any way to make it as I want?

Oki Erie Rinaldi
  • 1,835
  • 1
  • 22
  • 31

1 Answers1

2

There are two ways to declare a JavaScript regex:

var disallowed_char=/\[/;
var disallowed_char=new RegExp("\\[");

When you use the second notation, you need to double escape the backslash because it is already an escape character in JavaScript strings.

Christophe
  • 27,383
  • 28
  • 97
  • 140