Regex

How to match string with brackets using regex in javascript

Question: How to match a string with brackets using regex in Javascript?

For matching a string that includes brackets in it you need to make a regex that needs to create a set of escaped (with \) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group. Here is an example of the same.

var regExp = /\(([^)]+)\)/;
var matches = regExp.exec("I expect five hundred dollars ($500).");

//matches[1] contains the value between the parentheses
console.log(matches[1]);

But if you have a case in which you want to match a complete string with brackets in its start and end using regex than you can follow the below-given regex. Here is an example of the same.

(\([A-Z]{2}\))

So, this is all about matching a string with brackets using regex in Javascript. Thanks for Reading! Although if you want to read more about regex, you can take reference from this article.

Leave a Comment