Languages
[Edit]
EN

TypeScript - get substring in brackets

0 points
Created by:
Lillie-Rose-Finnegan
489

In this article, we would like to show you how to get substring in brackets in TypeScript.

Quick solution:

const substrings: string[] = text.match(/\[(.*?)\]/g);  // array of substrings surrounded with []

 

Practical example

In this example, we use the match() method with /\[(.*?)\]/g regex which matches everything in between the square brackets ([]).

const text: string = 'Example values: [value1] and [value2].';

const matches: string[] = text.match(/\[(.*?)\]/g);

if (matches) {
  for (let i = 0; i < matches.length; ++i) {
    const match = matches[i];
    const substring = match.substring(1, match.length - 1); // brackets removing
    console.log(substring);
  }
}

Output:

value1
value2

Reusable function

In this section, you will find a reusable function that will let you extract substrings surrounded with [ and ];

const getValues = (text: string): string[] => {
  const matches = text.match(/\[(.*?)\]/g);
  const result = [];
  if (matches) {
    for (let i = 0; i < matches.length; ++i) {
      const match = matches[i];
      result.push(match.substring(1, match.length - 1)); // brackets removing
    }
  }
  return result;
};


// Usage example:

const text: string = 'Example values: [value1] and [value2].';
const values: string[] = getValues(text);

console.log('Result: ' + values);

Output:

Result: value1,value2

Iterative solution

In this section, we present an iterative solution of how to get substring in brackets.

const text: string = 'Example values: [value1] and [value2].';

for (let i = 0, j = 0; ; ) {
  i = text.indexOf('[', i);
  if (i !== -1) {
    i = i + 1;
    j = text.indexOf(']', i);
    if (j !== -1) {
      console.log(text.substring(i, j));
      i = j + 1;
      continue;
    }
  }
  break;
}

Output:

value1
value2

Note:

The advantage of this approach is high efficiency.

See also

  1. JavaScript - get substring in brackets

Alternative titles

  1. TypeScript - get substring in square brackets
  2. TypeScript - get substring between brackets
  3. TypeScript - find text between square brackets
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join