Sometimes, we want to return string between square brackets with JavaScript.
In this article, we’ll look at how to return string between square brackets with JavaScript.
How to return string between square brackets with JavaScript?
To return string between square brackets with JavaScript, we use the string match
method.
For instance, we write
const matches = myString.match(/[(.*?)]/);
if (matches) {
const [, subMatch] = matches;
}
to call myString.match
with a regex that matches the string between brackets.
(.*?)
inside the brackets matches the group within the brackets.
Then we get the match from subMatch
in the 2nd entry of the matches
array.
Conclusion
To return string between square brackets with JavaScript, we use the string match
method.