JavaScript: Pad (left, right) a string to get to a determined length
JavaScript String: Exercise-20 with Solution
Pad String to Length
Write a JavaScript function that can pad (left, right) a string to get to a specific length.
Test Data:
console.log(formatted_string('0000',123,'l'));
console.log(formatted_string('00000000',123,''));
Output:
"0123"
"12300000"
Visual Presentation:

Sample Solution:
JavaScript Code:
Output:
0123 12300000
Explanation:
The above JavaScript code defines a function "formatted_string()" that takes three parameters: 'pad', 'user_str', and 'pad_pos'. Here's a brief explanation -
- The function checks if 'user_str' is 'undefined'. If so, it returns 'pad'.
- If 'pad_pos' is 'l' (indicating left padding), it concatenates 'pad' with 'user_str', keeps only the last characters equal to the length of 'pad', and returns the result.
- If 'pad_pos' is not 'l', it concatenates 'user_str' with 'pad', keeps only the characters equal to the length of 'pad', and returns the result.
Flowchart:

Live Demo:
For more Practice: Solve these Related Problems:
- Write a JavaScript function that pads a string on the left or right to reach a specified length using a given character.
- Write a JavaScript function that validates the pad direction parameter and returns an error for invalid directions.
- Write a JavaScript function that uses string concatenation to pad a string without using built-in padStart/padEnd.
- Write a JavaScript function that handles numeric inputs by converting them to strings before padding.
Improve this sample solution and post your code through Disqus.
Previous: Reverse a Binary string.
Next: Repeat a string a specified times.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.