How can I retrieve the word my
from between the two rounded brackets in the following sentence using a regex in JavaScript?
"This is (my) simple text"
Curly brackets { and } are also known as "curly braces" or simply "braces" (UK and US), "definite brackets", "swirly brackets", "birdie brackets", "French brackets", "Scottish brackets", "squirrelly brackets", "gullwings", "seagulls", "squiggly brackets", "twirly brackets", "Tuborg brackets" (DK), "accolades" (NL), " ...
Parentheses Create Numbered Capturing Groups Besides grouping part of a regular expression together, parentheses also create a numbered capturing group. It stores the part of the string matched by the part of the regular expression inside the parentheses. The regex Set(Value)? matches Set or SetValue.
console.log( "This is (my) simple text".match(/\(([^)]+)\)/)[1] );
\(
being opening brace, (
— start of subexpression, [^)]+
— anything but closing parenthesis one or more times (you may want to replace +
with *
), )
— end of subexpression, \)
— closing brace. The match()
returns an array ["(my)","my"]
from which the second element is extracted.
var txt = "This is (my) simple text"; re = /\((.*)\)/; console.log(txt.match(re)[1]);
jsFiddle example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With