简体   繁体   English

JavaScript:使用自动换行格式化文本

[英]JavaScript: Formatting text with word wrap

I have a logger object that formats log messages with a timestamp, sender, and formats lines to a maximum of 80 characters in length.我有一个记录器对象,它使用时间戳、发件人格式化日志消息,并将行格式化为最多 80 个字符的长度。

var paddedSender = message.Sender.padStart( 6 );
var string = `=-[ ${message.Timestamp} ][ ${paddedSender} ] `;
var remainingLength = this.CONSOLE_MAX_LENGTH - string.length - 3;

var lines = [];
var numLines = Math.ceil( message.Body.length / remainingLength );
for ( var i = 0, o = 0; i < numLines; i++ , o += remainingLength )
  lines.push( message.Body.substr( o, remainingLength ) );

string += lines.shift().padEnd( remainingLength ) + ' -=';
while ( lines.length > 0 )
  string += '\n'
    + '=-'
    + '-'.repeat( message.Timestamp.length + 4 )
    + '-'.repeat( paddedSender.length + 4 )
    + ` ${lines.shift().padEnd( remainingLength )} `
    + '-=';

return string;

This results an output similar to the following:这会产生类似于以下内容的输出:

================================================================================
=-[ 06/08 11:30:36 ][ SYSTEM ] Initializing...                                -=
=-[ 06/08 11:30:36 ][ SYSTEM ] Logger Initialized                             -=
=-[ 06/08 11:30:37 ][ SYSTEM ] WebService Initialized                         -=
=-[ 06/08 11:30:38 ][ WEBCLI ] API Returned 400 Bad Request(Endpoint: undefin -=
=----------------------------- ed) (Err: Invalid id)                          -=

So far it acts as intended.到目前为止,它按预期运行。 However, I would like to have it word wrap by starting new lines between spaces instead of when the character limit is hit.但是,我希望通过在空格之间开始新行而不是在达到字符限制时使其自动换行。

For instance, I would like this message:例如,我想要这条消息:

=-[ 06/08 11:30:38 ][ WEBCLI ] API Returned 400 Bad Request(Endpoint: undefin -=
=----------------------------- ed) (Err: Invalid id)                          -=

To be formatted like so:要像这样格式化:

=-[ 06/08 11:30:38 ][ WEBCLI ] API Returned 400 Bad Request(Endpoint:         -=
=----------------------------- undefined) (Err: Invalid id)                   -=

How can I achieve this?我怎样才能做到这一点?

You could take the text and take a wanted size and check if the position of the end of the part string is an space, then split the string and push it to an array with an adjustment for the length.您可以获取文本并获取所需的size并检查部分字符串末尾的位置是否为空格,然后拆分字符串并将其推送到调整长度的数组。

 var string = 'API Returned 400 Bad Request(Endpoint: undefined) (Err: Invalid id) Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.', size = 46, parts = [], start = 0, end; while (start <= string.length) { end = start + size; if (end < string.length) while (string[end] !== ' ') --end; parts.push(string.slice(start, end).padEnd(size, ' ')); start = end + 1; } console.log(parts);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM