在javascript中为字符串添加填充间距

Adding pad spacing to string within javascript

本文关键字:填充 添加 字符串 javascript      更新时间:2023-09-26

我有一个应用程序正在向另一个系统发送变量,该系统要求变量为16个字符。但是,用户不需要输入16位数字。

这是我迄今为止的编码:

在文件中激活javascript:

<A HREF="javascript:onClick=creditlink()" title="Enter own credit memo number.">Create Credit Memo</a>

这是我正在使用的javascript:

function creditlink ()
{
var cmnum2 = document.getElementById('creditmemo').value;
var cmnum = document.getElementById('autocmnum').value;
var clmid = document.getElementById('claimid').value;
//alert (cmnum);
if (cmnum2) {

window.open("https://somewebpage.cfm?creditmemos=" + cmnum2 + "&claimid=" +clmid );
}
//This is the customer did not want to enter their own number one would be auto generated
else {
window.open("https://somewebpage.cfm?creditmemos=" + cmnum + "&claimid=" +clmid );
}
}

因此,在我需要cmnum2帮助的地方,我需要在链接中发送之前将其转换为16个字符。仅供参考,此功能运行良好。

所以我的想法是在值之前添加空格填充,使其等于16个字符。下面是我需要的一个例子:

用户输入:cmnum2="61150331"(8个字符)新值:cmnum2="(8个空格)61150331"(总共16个带空格的字符)

我相信我已经看到过用string.format或string padleft或padright这样的函数来完成它,但我不确定编码格式如何使其成为16,无论值是多少。

这里有一个使用ES6(Harmony)函数String.prototype.repeak的例子。我已经为您提供了polyfils,或者您可以使用ES6填充程序。无论如何,这只是一个进一步的例子,说明可以做什么,什么将成为标准。

Javascript

// ES6 - Harmony polyfils
if (typeof Math.sign !== "function") {
    Math.sign = function (n) {
        if (n < 0) {
            return -1;
        }
        return 1;
    };
}
if (typeof Number.toInteger !== "function") {
    Number.toInteger = function (value) {
        var n = +value;
        if (isNaN(n)) {
            return +0;
        }
        if (n === 0 || !isFinite(n)) {
            return n;
        }
        return Math.sign(n) * Math.floor(Math.abs(n));
    }
}
if (typeof String.prototype.repeat !== "function") {
    String.prototype.repeat = (function () {
        var repeat = function (s, times) {
            if (times < 1) {
                return "";
            }
            if (times % 2) {
                return repeat(s, times - 1) + s;
            }
            var half = repeat(s, times / 2);
            return half + half;
        };
        return function (times) {
            times = Number.toInteger(times);
            if (times < 0 || times === Infinity) {
                throw new RangeError();
            }
            return repeat(String(this), times);
        };
    }());
}
// Helper function
function clamp(num, min, max) {
    return Math.min(Math.max(num, min), max);
};
// The padding function
function pad(userString) {
    return " ".repeat(clamp(16 - userString.length, 0, 16)) + userString;
}
// Example usage
var input = "12345",
    output = pad(input);
console.log(input, input.length, output, output.length);

输出

12345 5            12345 16 

jsfidd

这里有一个可能的解决方案。请注意,如果字符串已经是16个(或更多)字符,则永远不会输入for循环。

function padTo16Chars(string) {
    var length = string.length;
    var newString = "";
    for (var index = 0; index < (16 - length) ; index++) {
        newString = newString + " ";
    }
    string = newString + string;
}

要使其工作,请在creditlink方法中调用此方法,如下所示:

function creditlink ()
{
    var cmnum2 = document.getElementById('creditmemo').value;
    padTo16Chars(cmnum2);
    //Other stuff
}

编辑:填充是在值之后,现在是在值之前。

实现这一点的一个简单方法是使用while循环:

while (cmnum2.length < 16) {
   cmnum2 = " " + cnmun2
}

但是,您可能希望将其放置在函数中,并返回添加了空格的新字符串。

var cmnum2 = "09872";
var num = function(cmnum2){
    while (cmnum2.length < 16) {
      cmnum2 = " " + cmnum2;
    }
    return cmnum2;
};
console.log(num(cmnum2)); //"(11spaces)09872"

希望能有所帮助。

我真的很喜欢Xotic750的答案。不过我还有其他东西:

/**
 * @description Pads given string 
 * @param {string} s The string to pad
 * @param {number} n The amount of spaces to pad
 * @returns {string} Left padded string.
 * @todo check parameters' types and allowed values, undefined, etc.
 */
function padLeft(s,n) {
    return ((s.length >= n) ? s : (new Array(n - s.length)).join(" ") + s);
}

这是一个非常简单的解决方案。。。