Strange regex issue

The following code works as a Caesar’s Cipher, however, I cannot figure out why if I make the regex global (/[A-Z]/g) it produces strange results. Where it gets even more strange is if I uncomment the .match() method in the middle, the cipher works again even though the global regex remains… if I uncomment the the .test() method in the middle I get even different results.

function rot13(str) {
    console.log(str);
    let reg = /[A-Z]/
    let alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ';
    let alphaArr = alpha.split('');
    let newStr = ''
    for (let i = 0; i < str.length; i++) {
      //console.log(str[i].match(reg))
      //console.log(reg.test(str[i]));
      if (reg.test(str[i])) {
        newStr += alphaArr[alphaArr.indexOf(str[i]) + 13]
      } else {
        newStr += str[i];
      }
    }
    return newStr;
  }
  
  console.log(rot13("SERR PBQR PNZC"));

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

Can you be more specific by what you mean by “strange”? What may seem strange to you may seem normal to someone that uses regex.

If I look in the docs (a habit every dev should nurture), I read that:

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g. /foo/g or /foo/y). They store a lastIndex from the previous match. Using this internally, test() can be used to iterate over multiple matches in a string of text (with capture groups).

In other words, with the g flag, it’s not starting new search each time but is continuing with the old one.

1 Like

Thank you! I will take a look at those docs!

1 Like

Aha… have you considered posting the “strange” results so we can also enjoy them? ^^

Yes sorry I should have been more clear…

The way it’s shown will return “FREE CODE CAMP”

Adding the global flag to the reflex returns “FEER CBDR CNMC”

Regex* (auto type)………………

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.