JavaScript - padEnd() method

revision:


Category : string

The padEnd() method pads a string at the end. The padEnd() method pads a string with another string (multiple times) until it reaches a given length.

The padEnd() method is a string method. To pad a number, convert the number to a string first.

Syntax :

        string.padEnd(length, string)
    

Parameters:

length : required. The length of the resulting string.

string : optional. The string to pad with. Default is space.

Examples:

        <p>The padEnd() method pads a string at the end.</p>
        <p>It pads the string with another string (multiple times) until it reaches a given length.</p>
        <p id="demo"></p>
        <script>
            let text = "5";
            text = text.padEnd(4,"0");
            document.getElementById("demo").innerHTML = text;
        </script>
    

Practical examples

example: padEnd() method with string and number.

code:
                    <div>
                        <p id="pad-1"></p>
                        <p id="pad-2"></p>
                        <p id="pad-3"></p>
                        <p id="pad-4"></p>
                        <p id="pad-5"></p>
                        <p id="pad-6"></p>
                        <p id="pad-7"></p>
                    </div>
                    <script>
                        let text = "5";
                        document.getElementById("pad-1").innerHTML = "text : " + text;
                        text1 = text.padEnd(4,"0");
                        document.getElementById("pad-2").innerHTML = "text padded : " + text1;
                        document.getElementById("pad-3").innerHTML = "text padded : " + text.padEnd(4,"x");
                        text2 = text.padEnd(4,"a");
                        document.getElementById("pad-4").innerHTML = "text padded : " + text2;
            
                        let numb = 5;
                        document.getElementById("pad-5").innerHTML = "number : " + numb;
                        let text3 = numb.toString();
                        document.getElementById("pad-6").innerHTML = "text padded : " + text.padEnd(4,"b");
            
                    </script>