首页 > 解决方案 > 将纯文本字符串格式化为对齐的两列

问题描述

我正在寻求有关如何在我正在开发的 Web 应用程序中更好地组织字符串输出的帮助。

输出到textarea 框,并且始终采用以下格式:

TITLE: Some short text here

或者

TITLE: Some longer text here that might get to the end of the line and wrap under the left column. I'd like to add the same padding to new lines so they are neatly under the right sided text column.

我添加.padEnd(25)到左列中的文本,为右列创建一个均匀的开始。但我不知道如何将字符串中的所有文本保持在超过 50 个字符的字符串下方对齐?

我想我需要根据space50 个字符后的第一个字符进行拆分,并将 25 个字符的左填充添加到每一行,它可能有效吗?但我无法弄清楚如何做到这一点,所以文本看起来像:

TITLE: Some short text here

NEXT: Some longer text here that might get to the end of the line and wrap under the left column. I'd like to add the same padding to new lines so they are neatly under the right sided text column.

一些用户会将其复制并粘贴到他们自己的文档中,这就是为什么我会遇到麻烦,试图在纯文本中以临时方式对其进行排序。

谢谢。

更新了用户输入的示例 HTML

<div class="input-group py-1">
    <span class="input-group-addon"> TITLE </span>
    <select class="form-control" id="ext-title">
        <option>The Hobbit</option>
        <option>Lord of the Rings</option>
        <option>Mortal Engines</option>
    </select>
</div>

<div class="input-group py-1">
    <span class="input-group-addon"> NEXT </span>
    <textarea class="form-control py-1 w-100" id="ext-long" rows="3" placeholder="Specify your ideas"></textarea>
</div>

和我的脚本样本

var ext_title = $("#ext-title").val();
var ext_long  = $("#ext-long").val();
var text      = '';
text          +=  "\nTITLE:".padEnd(25) + ext_title +
                  "\nNEXT:".padEnd(25) + ext_long + "\n";

标签: javascriptjquerystring

解决方案


CSS来救援:)

(我们毕竟是 JS 开发人员吗?)

HTML

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="styles.css">
    </head>
<body>
    <div class="section">
        <span class="title">Title</span>
        <span class="column">
            Heres my long text which needs to potentially longer that 50 characters
        </span>
    </div>
    <div class="section">
        <span class="title">Title</span>
        <span class="column">
            Heres my long text which needs to potentially longer that 50 characters
        </span>
    </div>
</body>
</html>

CSS (样式.css)

.section {
    display: flex;
    margin-bottom: 10px;
}

.column {
    margin-left: 100px;
}

使用 margin-left 指定与标题的距离,单词将环绕但会粘在由“列”跨度定义的列中


推荐阅读