* Prepends line numbers to each line of a string. * The line numbers will be left-padded with spaces to ensure an * aligned layout when rendered using monospace fonts. * @param {String} string - multi-line string to add line numbers to * @param {Number} start=1 - number of spaces to add * @para
(string)
| 3225 | |
| 3226 | |
| 3227 | function addLineNumbers(string) { |
| 3228 | var start = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; |
| 3229 | var delim = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : ': '; |
| 3230 | var lines = string.split(/\r?\n/); |
| 3231 | var maxDigits = String(lines.length + start - 1).length; |
| 3232 | return lines.map(function (line, i) { |
| 3233 | var lineNumber = i + start; |
| 3234 | var digits = String(lineNumber).length; |
| 3235 | var prefix = padLeft(lineNumber, maxDigits - digits); |
| 3236 | return prefix + delim + line; |
| 3237 | }); |
| 3238 | } |
| 3239 | /** |
| 3240 | * Pads a string with a number of spaces (space characters) to the left |
| 3241 | * @param {String} string - string to pad |
no test coverage detected