Advertisement
dimipan80

Palindromes

Nov 12th, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* Write a JavaScript function findPalindromes(str) that extracts from a given text all palindromes,
  2. e.g. "ABBA", "lamal", "exe". Write JS program palindromesExtract.js that invokes your function
  3. with the sample input data below and prints the output at the console. */
  4.  
  5. "use strict";
  6.  
  7. function findPalindromes(str) {
  8.     var arr = str.split(/\W+/).filter(Boolean);
  9.     var resultArr = [];
  10.     for (var i = 0; i < arr.length; i += 1) {
  11.         if (arr[i].length == 1) {
  12.             resultArr.push(arr[i]);
  13.         } else {
  14.             var word = arr[i].toLowerCase();
  15.             var reverseWord = '';
  16.             for (var j = word.length - 1; j >= 0; j -= 1) {
  17.                 reverseWord += word[j];
  18.             }
  19.  
  20.             if (reverseWord == word) resultArr.push(word);
  21.         }
  22.     }
  23.  
  24.     return resultArr.join(', ');
  25. }
  26.  
  27. console.log(findPalindromes('There is a man, his name was Bob.'));
  28. console.log(findPalindromes('Javaj sos mam dad'));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement