javascript caesar密码算法 [英] javascript caesar cipher algorithm
问题描述
有没有做这个功能?,因为我觉得很难理解,特别是一个char参数表的功能,我不知道我在哪里或如何使用它。
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.
function trans(msg, rot) {
//Reemplaza cada letra encontrada de la expresion [a-z], por el caracter codificado de la funcion
return msg.replace(/([a-z])/ig,
function(char) {
var codASCII = char.charCodeAt(0);
return String.fromCharCode( codASCII >= 97 ? (codASCII + rot + 26 - 97) % 26 + 97 : (codASCII + rot + 26 - 65) % 26 + 65 );
});
}
提前谢谢你
推荐答案
让我们来看看 String.replace
的功能定义:
Let us have a look at String.replace
's function definition:
str.replace(regexp|substr, newSubStr|function [, flags]);
在JavaScript中,我们可以将替换函数传递给 String.replace
函数。描述函数的参数如下所述:在本节的MDN文章。
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.
基本上:
- 第一个参数是与整个表达式匹配的字符串(相当于替换字符串中的
$&
) - 随后的内容的捕获组(相当于
$ n
其中n
是正数)。 - 跟随主要匹配的偏移量
- 最后一个参数是输入字符串
- 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.
所以与 /([az])/ ig
作为第一个参数(在这种情况下为 char
)提供给替换函数。匹配的字符将被替换。
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.
在您的代码中, /([az])/ ig
可以简化为 / [az] / ig
,因为替换功能仅指主要匹配。
In your code, /([a-z])/ig
can be simplified to /[a-z]/ig
, since the replacement function only refers to the main match.
这篇关于javascript caesar密码算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!