Is there a function that fills a string up to a certain length?

3

I would like to populate a string until it reaches a certain length. Is there a function that can do this?

It would look something like PadLeft(Int32,Char) and <

    

asked by anonymous 19.07.2017 / 16:48

2 answers

4

Running on any version of JavaScript.

function padRight(str, len, char) {
    if (typeof(char) === 'undefined') {
        char = ' ';
    }
    len = len + 1 - str.length
    len = len  > 0 ? len : 0
    return Array(len).join(char) + str;
}

function padLeft(str, len, char) {
    if (typeof(char) === 'undefined') {
        char = ' ';
    }
    len = len + 1 - str.length
    len = len  > 0 ? len : 0
    return str + Array(len).join(char);
}

console.log(padLeft("teste", 8));
console.log(padLeft("teste", 8, '_'));
console.log(padLeft("teste e mais teste", 8, '_'));
console.log(padRight("teste", 8));
console.log(padRight("teste", 8, '_'));
console.log(padRight("teste e mais teste", 8, '_'));

I placed GitHub for future reference .

    
19.07.2017 / 17:18
3

From the ES8 , launched at the end of June, there are the following functions :

padStart(targetLength, padString) and padEnd(targetLength, padString) that fill a string with the specified content until it reaches a certain length.

Here are some examples of its use:

var str = "abc";

console.log("padStart: "+ str.padStart(1,"1"));
console.log("padStart: "+str.padStart(3,"1"));
console.log("padStart: "+str.padStart(6,123));
console.log("padStart: "+str.padStart(6,"%%%"));
console.log("----------------------");
console.log("padEnd: "+str.padEnd(1,"1"));
console.log("padEnd: "+str.padEnd(3,"1"));
console.log("padEnd: "+str.padEnd(6,123));
console.log("padEnd: "+str.padEnd(6,"%%%"));
    
19.07.2017 / 16:48