How to use loops In Javascript
A while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax :
while (boolean condition) {
loop statements...
}
Example:
function padStr(padChar, padLength, originalString) {
newString = originalString;
// Loop until desired length is reached
while (newString.length < padLength) {
// Add padChar each time
paddedString = padChar + paddedString;
}
return newString;
}
function pad() {
// Input string
example1 = "abcdefg";
example2 = 1234;
console.log(example1);
console.log(example2);
// Padded string
prepended_out = String(example1).padStart(10, '*');
prepended_out2 = String(example2).padStart(10, '^#');
// Display output
console.log(prepended_out);
console.log(prepended_out2);
}
// Function Cal
pad();
Output
abcdefg 1234 ***abcdefg ^#^#^#1234
How to pad a string to get the determined length using JavaScript ?
In this article, we will pad a string to get the determined length using JavaScript. To achieve this we have a few methods in javascript which are described below: