Categories
JavaScript Answers

How to return string between square brackets with JavaScript?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *