javascript - get current line number (in current script)
JavaScript[Edit]
+
0
-
0
JavaScript - get current line number (in current script)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56// Hint: JavaScript API doesn't support get current line operation, but it is possible to do it using some trick. var NEWLINE_EXPRESSION = /\r\n|\n/g; var POSITION_EXPRESSION = /:(\d+):\d+\)?$/g; function splitLines(text) { return text.split(NEWLINE_EXPRESSION); } function findMatching(expression, text) { expression.lastIndex = 0; return expression.exec(text); } function getLine() { var error = new Error(); if (!error.stack) { try { throw error; // error is thrown to get stack } catch (e) { if (!e.stack) { return null; } } } var lines = splitLines(error.stack); for (var i = 0, j = 0; i < lines.length; i += 1) { var match = findMatching(POSITION_EXPRESSION, lines[i]); if (match) { if (j === 1) { return parseInt(match[1]); } j += 1; } } return null; } // Usage example: console.log(getLine()); // 43 console.log(getLine()); // 44 console.log(getLine()); // 45 console.log(getLine()); // 46 console.log(getLine()); // 47 // Tested under: // - Google Chrome // - Mozilla Firefox // - Microsoft Edge // - Microsoft IE10+ // - Apple Safari // - Node.js
Reset