String Operation in javascript

1)Write a code to reverse a string

Way 1 :

split the string into array

reverse the array

join the array

Programme :

<div id="id1"></div>
<script>
var str = "apple";
var arr = str.split("");
var newArr = arr.reverse();
var newString = newArr.join("");
document.getElementById("id1").innerHTML = newString;
</script>

Way 2 :

Loop through the main string

Concatenate through the reverse string

<div id="id1"></div>

<script>

var str = 'apple';
var mainStr = '';
for(x of str){
mainStr = x+mainStr;
}
document.getElementById("id1").innerHTML = mainStr;
</script>

2)Write a code for the palindrome. 

Note : If any string or number gets reversed then it marches the original value

Example : akka , kayak , level

Way 1 :

<div id=”id1″></div>
<script>
var str = ‘apple’;
var mainStr = ”;
for(x of str){
mainStr = x+mainStr;
}
document.getElementById(“id1”).innerHTML = str + “==” + mainStr;
if(str==mainStr){
document.getElementById(“id1”).innerHTML = “It is palindrom”;
}
else{
document.getElementById(“id1”).innerHTML = “It is not a palindrom”;
}

</string>

By : Pankaj kumar agarwal

Leave a reply:

Your email address will not be published.