JavaScript Question Practice For Logic Building
Q . Write a JavaScript program to check whether
a given integer is within 20 of 100 or 400.
solution
function testhundred(x) {
return ((Math.abs(100 - x) <= 20) ||
(Math.abs(400 - x) <= 20));
}
console.log(testhundred(10));
console.log(testhundred(90));
Q . Write a JavaScript program to check two given
integers whether one is positive and another one is negative.
solution
function check(a,b){
if((a < 0 && b > 0) || a > 0 && b < 0) {
return true ;
}
else{
return false;
}
}
console.log(check(2,2))
console.log(check(2,-2))
console.log(check(-2,2))
console.log(check(-2,-2))
Q. Write a JavaScript program to create another string
by adding "Py" in front of a given string. If the given
string begins with "Py" return the original string.
Solution
function string_check(str1) {
if (str1 === null || str1 === undefined || str1.substring(0, 2) === 'Py')
{
return str1;
}
return "Py"+str1;
}
console.log(string_check("Python"));
console.log(string_check("thon"));
Q . Write a JavaScript program to remove a character at the
specified position in a given string and return the modified string
Solution
function removestr(){
let str1 = "Hi getcodr" ;
let str2 = str1.replace('Hi ','') ;
return str2 ;
}
console.log(removestr()) ;
Q. Write a JavaScript program to create a new string from a
given string by changing the position of the first and last
characters. The string length must be broader than or equal to 1.
Solution
function first_last(str1){
if(str1.length <= 1){
return str1 ;
}
newstr = str1.substring(1, str1.length - 1) ;
return (str1.charAt(str1.length - 1)) + newstr + str1.charAt(0) ;
}
console.log(first_last('ram'));
No comments:
Post a Comment