- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Reversing the prime length words - JavaScript
We are required to write a JavaScript function that takes in a string that contains strings joined by whitespaces. Our function should create a new string that has all the words from the original string and the words whose length is a prime number reversed i.e. words with length 2, 3, 5, 7, 100, etc.
Example
Following is the code −
const str = 'His father is an engineer by profession'; // helper functions const isPrime = n => { if (n===1){ return false; }else if(n === 2){ return true; }else{ for(let x = 2; x < n; x++){ if(n % x === 0){ return false; } } return true; }; }; const reverseString = str => str.split('').reverse().join(''); const reversePrime = str => { return str.split(' ').reduce((acc, val) => { const { length } = val; if(isPrime(length)){ acc += reverseString(val)+' '; }else{ acc += val+' '; }; return acc; }, ''); }; console.log(reversePrime(str));
Output
Following is the output in the console −
siH father si na engineer yb profession
Advertisements