Here is a revised version that caters to the distinctions between Firefox, Chrome, and Internet Explorer stack traces. It eliminates the initial "ERROR" line from Chrome and IE, making it notably quicker than other variants mentioned here.
// stack: string - call stack string
// levels: int - number of levels to remove from the top of the call stack
function trimCallStack(stack, levels) {
if (stack) {
const newLineChar = "\n"; // Each line delimited by '\n'
const isFirefoxCallStack = stack.indexOf("@") > -1; // If stacktrace contains '@' it is FireFox
// Remove an extra line if browser isn't FireFox (i.e., Chrome or IE) as they start the stack trace with the error name
// Remove N additional lines specified by `levels`
let iterations = (isFirefoxCallStack ? 0 : 1) + (levels ?? 0);
let start = 0;
while(iterations-- && start !== -1) {
start = stack.indexOf(newLineChar, start + 1);
}
stack = start !== -1 ? stack.substring(start + 1) : ""; // start === -1 if removing more lines than exist, so return "" in that case
}
return stack || "";
}
Examples of stack traces from Firefox and Chrome/IE:
Chrome/IE stacktrace:
Error: fail
at test (<anonymous>:2:8)
at test1 (<anonymous>:5:5)
at test2 (<anonymous>:8:5)
at test3 (<anonymous>:11:5)
at <anonymous>:1:5
Firefox stacktrace:
test@debugger eval code:2:8
test1@debugger eval code:5:5
test2@debugger eval code:8:5
test3@debugger eval code:11:5
@debugger eval code:1:5
After implementing the provided function:
Chrome/IE stacktrace:
at test (<anonymous>:2:8)
at test1 (<anonymous>:5:5)
at test2 (<anonymous>:8:5)
at test3 (<anonymous>:11:5)
at <anonymous>:1:5
Firefox stacktrace:
test@debugger eval code:2:8
test1@debugger eval code:5:5
test2@debugger eval code:8:5
test3@debugger eval code:11:5
@debugger eval code:1:5