हमें एक 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