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

Asked

Viewed 209 times

6

I’d like to fill out a string until it reaches a certain length. There is some function capable of doing this?

It would be something like the PadLeft(Int32,Char) and PadRight(Int32,Char) of the C#.

2 answers

7

From the Ecmascript 2017 (ES8), the following methods have been implemented:

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

Here are some examples of its use:

let 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,"%%%"));

6


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 put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.