user1978340
user1978340

Reputation: 101

Adding pad spacing to string within javascript

I have an application that is sending a variable to another system which requires the variable to be 16 characters. However, the user is not required to enter a 16 digit number.

Here is the coding I have so far:

Within the file to activate the javascript:

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

Here is the javascript I am using:

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 );

}

}

So here where I need help for cmnum2 I need it to be turned into 16 characters before it is sent in the link. FYI this function is working great.

So my thought was to just add space padding before the value to equal 16characters. Here is a example of what I need:

User enter: cmnum2 = "61150331" (8 characters) New value: cmnum2 = "(8 spaces)61150331" (total 16 characters with spaces)

I believe I have seen it done with functions like string.format or string padleft or padright but I am not sure how the coding format would work to make it 16 no matter what the value is.

Upvotes: 0

Views: 3595

Answers (4)

Sebas
Sebas

Reputation: 21532

I really like Xotic750's answer. I had something else though:

/**
 * @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);
}

It's a pretty straightforward solution...

Upvotes: 0

Bryan
Bryan

Reputation: 2078

A simple way to accomplish this would be to use a while loop:

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

However you would probably want to place that within a function and return the new string with added spaces.

var cmnum2 = "09872";

var num = function(cmnum2){
    while (cmnum2.length < 16) {
      cmnum2 = " " + cmnum2;
    }
    return cmnum2;
};

console.log(num(cmnum2)); //"(11spaces)09872"

Hope that helps.

Upvotes: 0

Xotic750
Xotic750

Reputation: 23472

Here is an example that uses ES6 (Harmony) functions, String.prototype.repeat. I've included the polyfils for you, or you could use ES6 shim. Anyway, this is just a further example of what can be done, and what will become standard.

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);

Output

12345 5            12345 16 

On jsfiddle

Upvotes: 1

Xynariz
Xynariz

Reputation: 1243

Here's one possible solution. Note that if the string is already 16 (or more) characters, the for loop will never be entered.

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

For this to work, put a call to this method inside your creditlink method, like so:

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

EDIT: The padding was after the value, now it's before.

Upvotes: 0

Related Questions