EN
TypeScript - get substring in brackets
0
points
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.