如何用内容填充段落?

How to fiil paragraph with content?

我想创建一个包含以下内容的段落:名称、成本(例如“3.66$”)。但问题是我想用点(“......”)填充 space 但我不知道如何。 我从数据库中获取值(名称和成本),每个名称都不相同,所以我想不出让 space 充满点的方法。 例如,行:

"apple                        20.58$"


"banana and ice cream          4.99$"


需要:

"apple ...................... 20.58$"


"banana and ice cream ........ 4.99$"

这是代码:

for (var i = 0; i < data.d.length; i++) {
    $(document).ready(function () {
        $("#ShowMenu").append(
            "<p style='text-align: left;margin: 0px;'>" +
                "<span style='font-size: large;font-weight: bold;float:left;'>" + data.d[i].title + "</span>" +
                "<span style='float:right;'>" + data.d[i].cost + "</span>" +
            "</p>"
        );
    });
}

If you are replacing a value (and not a regular expression), only the first instance of the value will be replaced. To replace all occurrences of a specified value, use the global (g) modifier (see "More Examples" below).

Souce.

问题是替换替换了第一个找到的匹配项。你可以这样做:

function replaceAll(input, what, withWhat) {
    while (input.indexOf(what) !== 0) {
        input = input.replace(what, withWhat);
    }
    return input;
}

但这既不高效也不优雅。要改进它,你需要使用正则表达式:

function replaceAll(input, what, withWhat) {
    return input.replace(new RegExp(what, 'g'), withWhat);
}

并致电 replaceAll。如果你想让它更通用,你可以这样做:

String.prototype.replaceAll = replaceAll;

编辑:

上面的答案来自假设文本是由 Javascript 生成的。从评论部分和问题编辑中可以看出,我的假设是错误的。实际情况是出现空格是因为 CSS 样式 float.

一个可能的解决方案是创建一个点字符的图像和另一个具有其他内容所需背景的图像。设置段落的背景图为带重复的点图,跨度的背景图为彩色图。

另一种可能的解决方案是不使用浮点数,而是使用 javascript 写入点,直到达到所需的宽度。这涉及标签测量并且很慢。

你可以像这样使用函数:

function getReceiptItem(name, cost, maxLength) {
  var dotsLength = maxLength - name.length - cost.length - '$'.length;

  if (dotsLength < 0) {
    name = name.substring(0, name.length + dotsLength);
    dotsLength = 0;
  }

  return name + Array(dotsLength).join('.') + cost + '$';
}

Full example

不要忘记为收据设置等宽字体,例如:

* {
  font-family: 'monospace';
}