Meaning that I simply want to strip the enclosing braces. I can match "{ this kind of stuff }" with:
"{stuff}".match(/{([^}]*)}/)[1]
Am I asking too much here?
Another example, I've got this javascript code as string:
{
var foo = {
bar: 1
};
var foo2 = {
bar: 2
};
}
I want to strip only the outside braces:
var foo = {
bar: 1
};
var foo2 = {
bar: 2
}
Try this (I based my code on this answer). It also knows to ignore brackets in strings and comments (single-line and multi-line) - as noted in the comment section of that answer:
var block = /* code block */
startIndex = /* index of first bracket */,
currPos = startIndex,
openBrackets = 0,
stillSearching = true,
waitForChar = false;
while (stillSearching && currPos <= block.length) {
var currChar = block.charAt(currPos);
if (!waitForChar) {
switch (currChar) {
case '{':
openBrackets++;
break;
case '}':
openBrackets--;
break;
case '"':
case "'":
waitForChar = currChar;
break;
case '/':
var nextChar = block.charAt(currPos + 1);
if (nextChar === '/') {
waitForChar = '\n';
} else if (nextChar === '*') {
waitForChar = '*/';
}
}
} else {
if (currChar === waitForChar) {
if (waitForChar === '"' || waitForChar === "'") {
block.charAt(currPos - 1) !== '\\' && (waitForChar = false);
} else {
waitForChar = false;
}
} else if (currChar === '*') {
block.charAt(currPos + 1) === '/' && (waitForChar = false);
}
}
currPos++
if (openBrackets === 0) { stillSearching = false; }
}
console.log(block.substring(startIndex , currPos)); // contents of the outermost brackets incl. everything inside
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With