-2

I would like to match these characters: [] () in a character class in a regex in javascript, how can I do that?

The solution in grep would be: (regex - brackets and parenthesis in character-class)

<script>
var text = "echo some text (some text in parenthesis) [some other in brackets]";
var patt = /[][()]/g
console.log(text.match(patt));
</script>

But this regex provides no match in JS

Cœur
  • 34,719
  • 24
  • 185
  • 251
nagy.zsolt.hun
  • 5,542
  • 8
  • 48
  • 82

2 Answers2

0

Your example uses square brackets' special meaning in regex. If you want them to be matched literally you need to escape them using the '\' character. You can check this example, and hover over the characters, to see each one's meaning using your example, and this for the working one.

iuliu.net
  • 5,825
  • 4
  • 42
  • 67
-1

You should escape the square brackets inside the regex pattern:

var text = "echo some text (some text in paranthesis) [some other in brackets]",
    patt = /[\]\[()]/g;

console.log(text.match(patt));  // ["(", ")", "[", "]"]
RomanPerekhrest
  • 75,918
  • 4
  • 51
  • 91