![]() | ||
|
Introduction:
Many javascript developers are missing functions provided by javascript. This is a simple program just append and prepend string if the given string length is less then 25. Many developers try with loop and long logic for this. Our question is why we not using built-in functions. Let me try with built-in functions.
Challenge:
Write a logic for below input:
Input | Output |
---|---|
Javascript Everywhere | Javascript Everywhere---- ~~~~Javascript Everywhere |
You are a good developer | You are a good developer- ~You are a good developer |
New | New---------------------- ~~~~~~~~~~~~~~~~~~~~~~New |
Challenges | Challenges--------------- ~~~~~~~~~~~~~~~Challenges |
Program Description: Write a program if the string length is 25 characters then add ~(tilde) sign at prefix and add -(dash) sign at postfix.
The program output is:
function stringModify(str) {
console.log(str.padEnd(25, '-'));
console.log(str.padStart(25, '~'));
}
Another program:
2)
function stringModify(str){
const sign1="-";
const sign2="~";
let output=str.length>25 ? str: str.concat(sign1.repeat(25 - str.length), '\n', sign2.repeat(25 - str.length), str);
return output;
}
console.log(stringModify("New"));
Explanation:
1) In the first program, we use the built-in function provided by javascript.
2) The function is padEnd and padStart
padEnd()
This is a string function. The padEnd() method adds a current string in the given string. So the result is reached to the given length. String added at end of the current string. Ex:
const str1 = 'Welcome to javascript';
console.log(str1.padEnd(25, '_'));
// expected output: "Welcome to javascript____"
const str2 = '1000';
console.log(str2.padEnd(5));
// expected output: "1000 "
The default replaces string is space.
padStart()
This is also a string function. The padStart() method also expand string. So the result is reached to the given length. String added at the starting of the current string. Ex:
const strTemp = 'Welcome to javascript';
console.log(strTemp.padStart(25, '_'));
// expected output: "____Welcome to javascript"
const numberVal = '500';
console.log(numberVal.padEnd(5));
// expected output: " 500"
The default replaces character is space.
Many ways you can do this but most useful and preferable is using the build-in function.
Other: Swap to a variable without using the third one. more than 3 solutions provided.
Swap to a variable without the help of the third variable