Basic JavaScript Programs to Remove Special Characters, Find Reverse of a String or Number

Below are few basic JavaScript programs with explanation to find Reverse of a String, Clean Junk Characters from a String and Find the Reverse of an Integer. These are also important from Interview point of view:

//1. Find Reverse of a String using JavaScript

var str = "JavaScript";
var len = str.length;
console.log(len); //10
var rev ="";
for(var ilen-1;i>=0;i--)
{
    rev=rev+str.charAt(i);
}
console.log(rev); //tpirSSavaJ


//2. Remove special characters/Junk values from a String using JavaScript

var str1 = "Junk!@#$% ha^s been Removed)(*&)";
s = str1.replace(/[^a-zA-Z0-9 ]/g,"");
console.log(s); //Junk has been Removed

//3. Find Reverse of an integer using JavaScript

var num = 12345;
var numrev = 0;
while (num!=0)
{
    numrev=numrev*10 + num%10
    //0*10 + 12345%10 => 0+5 ==> 5
    //5*10 + 1234%10 => 50+4 ==> 54
    //54*10 + 123%10 => 540+3 ==> 543
    //543*10 + 12%10 => 5430+2 ==> 5432
    //5432*10 + 1%10 => 54320+1 ==> 54321 
    num=Math.floor(num/10); 
    //1234
    //123
    //12
    //1
}
console.log(numrev); //54321

0 comments:

Post a Comment

Thanks a lot for your valuable Comment!