JavaScript String padEnd() 方法使用指定的 padString 填充(或扩展)当前字符串以达到给定的长度。填充将添加到当前字符串的末尾。如有必要,可以重复多次,如果我们没有为此方法指定此可选参数 padString,它会在此字符串的末尾添加空格作为填充以达到指定的长度。
填充字符串时,将字符添加到字符串的末尾,直到它达到特定长度。
语法
以下是 JavaScript String padEnd() 方法的语法 -
padEnd(targetLength, padString)
参数
此方法接受两个名为 “targetLength” 和 “padString” 的参数,如下所述 -
- targetLength − 新字符串的长度。
- padString − 用于填充(扩展)当前字符串的字符串。
返回值
此方法返回指定 targetLength 的新字符串,并在末尾附加 padString。
示例 1
如果省略 padString 参数,它将通过在当前字符串的末尾添加空格作为填充来扩展字符串,直到它达到指定的 targetLength。
在以下示例中,我们使用 JavaScript String padEnd() 方法填充(扩展)字符串,并在此字符串 “QikepuCom” 的末尾填充(扩展)带空格的字符串,直到它达到指定的 targetLength 30。
<html>
<head>
<title>JavaScript String padEnd() Method</title>
</head>
<body>
<script>
const str = "QikepuCom";
document.write("原始字符串: ", str);
new_str = "";
document.write("<br>添加填充之前的新字符串长度: ",new_str.length);
const targetLength = 30;
document.write("<br>目标长度: ", targetLength);
// 使用padEnd()方法
new_str = str.padEnd(targetLength);
document.write("<br>将填充后的新字符串添加到此字符串的末尾: ", new_str);
document.write("<br>添加填充后的新字符串长度: ",new_str.length);
</script>
</body>
</html>
输出
上面的程序返回一个新的字符串填充,字符串 “QikepuCom” 的末尾有空格。
添加填充之前的新字符串长度: 0
目标长度: 30
将填充后的新字符串添加到此字符串的末尾: QikepuCom
添加填充后的新字符串长度: 30
示例 2
如果 padString 和 targetLength 参数都传递给此方法,它会通过在末尾添加 padString 来扩展字符串,直到它达到一定长度。
以下是 JavaScript String padEnd() 方法的另一个示例。我们使用此方法在字符串末尾添加指定的 padString “#” 来扩展此字符串 “Hello World”,直到它达到指定的 targetLength 15。
<html>
<head>
<title>JavaScript String padEnd() Method</title>
</head>
<body>
<script>
const str = "Hello World";
document.write("原始字符串: ", str);
new_str = "";
document.write("<br>添加填充之前的新字符串长度: ",new_str.length);
const targetLength = 15;
const padString = "#";
document.write("<br>目标长度: ", targetLength);
document.write("<br>Pad 字符串: ", padString);
// 使用padEnd()方法
new_str = str.padEnd(targetLength, padString);
document.write("<br>将填充后的新字符串添加到此字符串的末尾: ", new_str);
document.write("<br>添加填充后的新字符串长度: ",new_str.length);
</script>
</body>
</html>
输出
执行上述程序后,它将返回一个末尾添加填充的新字符串。
添加填充之前的新字符串长度: 0
目标长度: 15
Pad 字符串: #
将填充后的新字符串添加到此字符串的末尾: Hello World####
添加填充后的新字符串长度: 15