ArticleZip > Javascript Return String Between Square Brackets

Javascript Return String Between Square Brackets

When working with JavaScript, you may come across scenarios where you need to extract certain parts of a string. One common task is to retrieve the text enclosed within square brackets in a given string. This can be particularly useful for parsing data or extracting specific information from a larger dataset. In this article, we will explore how to easily extract the string located between square brackets using JavaScript.

To achieve this task, we can make use of regular expressions in JavaScript. Regular expressions provide a powerful and flexible way to search, manipulate, and extract text based on patterns. Specifically, we can define a regular expression pattern that matches text enclosed within square brackets.

First, let's define a sample string that contains text within square brackets:

Javascript

const sampleString = "This is a [sample] string with [square] brackets.";

Next, we will write a JavaScript function to extract the text within square brackets:

Javascript

function extractTextInSquareBrackets(inputString) {
    const pattern = /[(.*?)]/g;
    const matches = [];
    let match;

    while (match = pattern.exec(inputString)) {
        matches.push(match[1]);
    }

    return matches;
}

const result = extractTextInSquareBrackets(sampleString);
console.log(result); // Output: ["sample", "square"]

In this function, we define a regular expression pattern `/[(.*?)]/g` to match text enclosed within square brackets. Here's a breakdown of the pattern:
- `[` and `]` are escape characters for the square brackets, ensuring that they are treated as literal characters in the pattern.
- `(.*?)` is a non-greedy match that captures any characters between the square brackets.
- `g` at the end of the pattern stands for the global flag, which allows us to find all matches in the input string.

We then use a `while` loop along with the `exec` method to iterate over all matches found in the input string. Each match is pushed into the `matches` array, containing the text within the square brackets.

By running the `extractTextInSquareBrackets` function with our `sampleString`, we obtain an array of strings that were found within square brackets in the input string.

Remember, regular expressions are a powerful tool in JavaScript for string manipulation, and understanding how to use them effectively can simplify complex text processing tasks. With this simple function, you can easily extract text between square brackets in JavaScript strings, enabling you to efficiently parse and extract relevant information from your data.