Skip to content

Instantly share code, notes, and snippets.

@tluyben
Created December 9, 2022 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tluyben/e4c70398b5c2f78d4d2ff32199c29ca2 to your computer and use it in GitHub Desktop.
Save tluyben/e4c70398b5c2f78d4d2ff32199c29ca2 to your computer and use it in GitHub Desktop.
match curly brackets
function getBrackets(str) {
// Initialize the stack to keep track of open braces
const stack = [];
// Initialize the result string
let result = "";
// Iterate over each character in the input string
for (let i = 0; i < str.length; i++) {
const char = str[i];
// If the character is an open brace, push it to the stack
if (char === "{") {
stack.push(i);
}
// If the character is a close brace, pop the last open brace from the stack
// and extract the substring between the open and close braces
if (char === "}") {
const start = stack.pop();
result = str.substring(start, i + 1);
}
}
// Return the result string
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment