- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
- Related Articles
- Reversing the even length words of a string in JavaScript
- Reversing words within a string JavaScript
- Reversing words in a string in JavaScript
- Reversing the words within keeping their order the same JavaScript
- Reversing words present in a string in JavaScript
- Reversing the order of words of a string in JavaScript
- Reverse only the odd length words - JavaScript
- Maximum length product of unique words in JavaScript
- Partially reversing an array - JavaScript
- Arranging words by their length in a sentence in JavaScript
- Reversing vowels in a string JavaScript
- Reversing and preserving spaces in JavaScript
- Reversing all alphabetic characters in JavaScript
- Reversing strings with a twist in JavaScript
- Reversing alphabets in a string using JavaScript

Advertisements