Let's say I have a string:
var str1 = '(The cat (goes (meow)))'
I want to get The cat (goes (meow))
from this, which is inside the first pair of parentheses.
Which regex can I use to get this?
Another example:
var str2 = 'The cat (goes (meow))'
Now I want to get goes (meow)
.
How would I go about doing this?
Use indexOf
& lastIndexOf
to get the first (
& last )
. The use substring to get the text in between these indexes
var str1 = '(The cat (goes (meow)))'; var str2 = 'The cat (goes (meow))'; function getSubstring(str) { var firstOpenBracket = str.indexOf('('); var firstClosingBracket = str.lastIndexOf(')'); var getValue = str.substring(firstOpenBracket + 1, firstClosingBracket); console.log(getValue) } getSubstring(str1); getSubstring(str2)
You can use this regex /\\((.*)\\)/
to match everything inside the outer most pair of parentheses. Try the code below.
var regEx = /\\((.*)\\)/; var str1 = '(The cat (goes (meow)))'; var res = str1.match(regEx); console.log(res[1]); var str2 = 'The cat (goes (meow))'; var res = str2.match(regEx); console.log(res[1]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.