How to match a substring within 2 square brackets using RegEx in Node.js

1 Answer

0 votes
function extractBracketedContent(text) {
    const pattern = /\[(.*?)\]/g;
    const matches = [];
    let match;

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

    return matches;
}

const input = "This is a [sample] string with [multiple] square [brackets].";
const extracted = extractBracketedContent(input);

extracted.forEach(item => {
    console.log(item);
});

 
 
 
/*
run:
  
sample
multiple
brackets
     
*/

 



answered Jul 19 by avibootz
...