0

I was doing a simple coderbyte string reverse exercise, but I find I'm having difficulty changing string indexes because having string.charAt() on the left side of an assignment seems to throw an error. What causes this? What's a better way to access and change characters in a string?

function FirstReverse(str) { 
  for(var i = 0; i < Math.floor(str.length / 2); i++){
   original = str.charAt(i); 
    str.charAt(i) = str.charAt(str.length - 1 - i);
    str.charAt(str.length - 1 - i) = original;
  }
  return str;       
}
gariepy
  • 3,576
  • 6
  • 21
  • 34
Caleb Jay
  • 2,159
  • 3
  • 32
  • 66
  • @Icepickle that doesn't work I just tried on my console. – Gaston Sanchez Feb 18 '16 at 19:26
  • 3
    Strings are immutable – adeneo Feb 18 '16 at 19:26
  • So I got a solution to the string reverser, but to clarify, the above errors because strings are immutable? `function stringReverse(str) { var stringOut = ""; for(var i = 0; i < str.length; i++){ stringOut += str.substr(str.length - 1 - i, 1); } return stringOut; } ` – Caleb Jay Feb 18 '16 at 19:37

3 Answers3

2

As adeneo mentioned, strings are immutable. But you could use a simple array to do the conversion.

I added the conversion for the result array (str.split('')) simply because otherwise the middle char of uneven length strings wouldn't be there

function FirstReverse(str) { 
  var result = str.split('');
  for(var i = 0, len = Math.floor(str.length / 2); i < len; i++){
   original = str.charAt(i); 
    result[i] = str.charAt(str.length - 1 - i);
    result[str.length - 1 - i] = original;
  }
  return result.join('');       
}

console.log(FirstReverse('abc'));
Community
  • 1
  • 1
Icepickle
  • 12,689
  • 3
  • 34
  • 48
0

Before doing the process you need to split() the string with '' as parameter and then at the end of the function just join the individual parts using the join() method.Rest of the code looks OK. You can also follow the below method to reverse a string as well. Its a simple split and join method..

 function reverseString(str) {

var arr= str.split("");

var rev=arr.reverse(); var newarr=rev.join("");

return newarr; }

reverseString("hello");

0

Check this out i have made a little simpler for you

<html>
<body>
<script>
function pal()
{


var temp;
var s="HIH";
var x=s.split("");
for(var i=0;i<s.length;i++)
{
var j=s.length-i-1;
if(j>=i)
{
temp=s.charAt(i);
s[i]=s.charAt(j);
s[j]=temp;
alert(s[i]+"---"+s[j]);


}
}
alert(s+"  Reverse is ----"+x.join(""));

if(x.join("")==s)
{
alert("Palindrome");


}
else
alert(" Not a Palindrome");




}
</script>
<input type="button" onclick="pal();">Check Palindrome
</body>
</html>