Languages
[Edit]
EN

JavaScript - get substring in brackets

3 points
Created by:
jarlh
325

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

Quick solution:

const substrings = 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 ([]).

// ONLINE-RUNNER:browser;

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

const matches = 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);  
	}
}

Reusable function

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

// ONLINE-RUNNER:browser;

const getValues = (text) => {
    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 = 'Example values: [value1] and [value2].';
const values = getValues(text);

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

Iterative solution

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

// ONLINE-RUNNER:browser;

const text = '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;
}

Note:

The advantage of this approach is high efficiency.

References

  1. String.prototype.match() - JavaScript | MDN
  2. String.prototype.replaceAll() - JavaScript | MDN
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