Str[index] VS str.charAt(index)

Str[index] VS str.charAt(index)
0

#1

Hi everyone)
While doing Caesars Cipher noticed one thing:

if (str[i].match(/[A-Z]/))

works not the same as:

if (str.charAt(i) == /[A-Z]/)

I’m not sure wether it is because of regular expression or maybe str(i) and str.charAt(i) returns different value.

I will be grateful for any response!

Complete code is here ( I commented line that doesn’t work)

function rot13(str) { // LBH QVQ VG!
  var arr=[]; var num = 0; var letter = "";
  for (var i = 0; i<str.length; i++) {
    if (str[i].match(/[A-Z]/)) {
    //if (str.charAt(i) === /[A-Z]/) {
      num = str.charCodeAt(i)-13;
      if (num < 65) { num += 26;}
      letter = String.fromCodePoint(num);
    }
    else {
      letter = str.charAt(i);
    }
    arr.push(letter);
  }
  str = arr.join("");
  return str;
}

// Change the inputs below to test
rot13("SERR CVMMN!");

#2

/A-Z/ is a regex literal. You can’t just compare it to a string (well, not in a meaningful sense) - that’s precisely what the match method is for.

This should work just as fine as your first example:

str.charAt(i).match(/[A-Z]/)

#3

charAt() returns a string, the other is a RegExp object, when you want to compare them Js converts object to string, so the regexp literal /[A-Z]/ becomes “/[A-Z]/” and it never equals to what charAt() returns. (If you want to avoid such implicit conversions use strict equality ===)

str[i] and str.charAt(i) return the same value. However, strings in Js are read-only, yet str[i] syntax may give you the impression that it can appear on the left-side of assignment, which is wrong. So it’s better to make a habit of using charAt() method.


#4

Thanks, i think now I get the idea!