繁体   English   中英

如何用前导空格填充字符串?

[英]How do I pad out a string with leading blanks?

我需要在UltraEdit脚本(JavaScript)中测试字符串$ A的长度,然后如果它小于x(例如:30),则用前导空格填充它。 在Stack Overflow上可以找到以下建议,但在UltraEdit脚本中似乎不起作用。

$AAA .= (" " x (35 - length($AAA)));

建议表示赞赏。

PS:UltraEdit使用JavaScript核心引擎编写脚本。

在UltraEdit脚本中使用的JavaScript核心中,没有函数可以将格式化的内容打印成字符串变量。

但是,创建带有前导空格或零的对齐字符串非常容易。

数字固定长度输出示例:

var nNumber = 30;            // number to output right aligned with 4 digits
var sAlignSpaces = "    ";   // string containing the spaces (or zeros) for aligning

// Convert integer number to decimal string.
var sNumber = nNumber.toString(10);
// Has the decimal string less than 4 characters as defined by sAlignSpaces?
if (sNumber.length < sAlignSpaces.length)
{
   // Build decimal string new with X spaces (here 2) from the alignment
   // spaces string and concatenate this string with the number string.
   sNumber = sAlignSpaces.substr(0,sAlignSpaces.length-sNumber.length) + sNumber;
}
// String sNumber has now always at least 4 characters with
// 0 to 3 leading spaces depending on decimal value of the number.

根据最高数字动态对齐正数的示例:

var nHighestNumber = 39428;  // highest number usually determined before
var nCurrentNumber = 23;     // current number to output right aligned

// Convert the highest number to a decimal string and get a copy
// of this string with every character replaced by character '0'.
// With highest number being 39428 the created string is "00000".
var sLeadingZeros = nHighestNumber.toString(10).replace(/./g,"0");

// Convert integer number to decimal string.
var sNumber = nCurrentNumber.toString(10);
// Has the decimal string of the current number less
// characters than the decimal string of the highest number?
if (sNumber.length < sLeadingZeros.length)
{
   // Build decimal string new with X (here 3) zeros from the alignment
   // string and concatenate this leading zero string with the number string.
   sNumber = sLeadingZeros.substr(0,sLeadingZeros.length-sNumber.length) + sNumber;
}
// String sNumber has now always at least 5 characters with 0 to 4
// leading zeros depending on decimal value of the positive number.

我认为您正在寻找的是:

http://msdn.microsoft.com/en-us/library/66f6d830.aspx

暂无
暂无

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

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