在 JavaScript 中用第 n 位后一个字母替换字母
我们需要编写一个 JavaScript 函数,它取一个字母字符串和一个数字(比如 n)。然后我们应该返回一个新字符串,其中所有字符都替换为相邻字母表中第 n 个字母之后相应的字母。
例如,如果字符串和数字为 −
const str = 'abcd'; const n = 2;
那么输出应该是 −
const output = 'cdef';
示例
代码如下 −
const str = 'abcd';
const n = 2;
const replaceNth = (str, n) => {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let i, pos, res = '';
for(i = 0; i < str.length; i++){
pos = alphabet.indexOf(str[i]);
res += alphabet[(pos + n) % alphabet.length];
};
return res;
};
console.log(replaceNth(str, n));输出
控制台中的输出将是 −
cdef
广告
数据结构
联网
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP