Javascript Caesar Cipher Algorithm
Is there anyway to do this function?, because i find it quite difficult to understand, specially that function with a char parammeter which i dont see where or how i use it. functi
Solution 1:
Let us have a look at String.replace
's function definition:
str.replace(regexp|substr, newSubStr|function [, flags]);
In JavaScript, we can pass a replacement function to the String.replace
function. How the arguments of the function is populated is described in this section of MDN article.
Basically:
- The first argument is the string that matches the whole expression (equivalent to
$&
in replacement string) - Followed by the content of the capturing groups (equivalent to
$n
wheren
is positive number). There will be as many arguments as the number of capturing groups. - Followed by offset of the main match
- And the last argument is the input string.
So whatever matched by /([a-z])/ig
will be supplied to the replacement function as the first argument (char
in this case). The character matched will be processed and returned as the replacement.
In your code, /([a-z])/ig
can be simplified to /[a-z]/ig
, since the replacement function only refers to the main match.
Post a Comment for "Javascript Caesar Cipher Algorithm"