LizQuen Update
LizQuen Update

Reputation: 61

Any alternative way of using this .charAt()?

I have a problem, when I used input[index] in the statement the reverse word didn't match the value of inputString. But this works in C#. When I try it in JavaScript is not working. I want to learn what are the other alternative way of .char() method. Can anybody solve my problem?

strReverse = "";
input = document.getElementById("inputValue").value;
i = input.length;

for(var j = i; j >= 0; j--) {
     strReverse = strReverse + input.charAt(j); // i used input[index]  
}

Upvotes: 0

Views: 4554

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50759

If you wish to use input[index] instead of input.charAt() then you need to address the issue that you are setting i = input.length;

So when you enter your loop for the first iteration, j will be equal to i. Meaning that you are trying to access the character at the index equal to the length of the string (when you do input[j]). However, as arrays and string indexing starts at zero in javascript (and in most languages), there is no index at i (the length of the string), but, there is an index at i-1, which will give the last character in the string. Thus, if you want to reverse your array using input[j] you need to start j in your for loop as j = i - 1.

Take a look at the snippet for a working example:

strReverse = "";
input = "level";
i = input.length;

for(var j = i-1; j >= 0; j--) {
     strReverse = strReverse + input[j]; // i used input[index]  
}

if(strReverse === input) {
  alert(input +" is a palindrome!")
} else {
  alert(input +" is not a palindrome!");
}

Upvotes: 1

Related Questions