I have a string where I’m trying to grab the integer inside. The string looks like:
"(2) This is a string"
I need to grap that 2. but it could be any number so I tried:
var str = "(2) this is a string";
var patt = /\(\d\)/;
var num = str.match(patt);
This doesn’t return the correct answer. Should I do a split on the () or is there a better regexp?
2 things. When you want to capture a segment form a matched string, you use
()to note that. So I just wrapped the\din parens to capture it.Second, in order to access the captured segments, you must drill into the returned array. the
matchmethod will return an array where the first item is the entire matched string, and the second item is any matched capture groups. So use[1]to fetch the first capture group (second item in array)