Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Encrypting a string based on an algorithm in JavaScript
Problem
We are required to write a JavaScript function that takes in a string and encrypts it based on the following algorithm −
- The string contains only space separated words.
- We need to encrypt each word in the string using the following rules −
- The first letter needs to be converted to its ASCII code.
- The second letter needs to be switched with the last letter.
Therefore, according to this, the string ‘good’ will be encrypted as ‘103doo’.
Example
Following is the code −
const str = 'good';
const encyptString = (str = '') => {
const [first, second] = str.split('');
const last = str[str.length - 1];
let res = '';
res += first.charCodeAt(0);
res += last;
for(let i = 2; i < str.length - 1; i++){
const el = str[i];
res += el;
};
res += second;
return res;
};
console.log(encyptString(str));
Output
Following is the console output −
103doo
Advertisements