javascriptswapcharat

swapping the first and last letters of every word in a string using javascript


Given a string of words separated by spaces, write a function that swaps the first and last letters of every word. You may assume that every word contains at least one letter, and that the string will always contain at least one word. You may also assume that each string contains nothing but words and spaces, and that there are no leading, trailing, or repeated spaces.

This is what I have so far

function first_last(str1){
 if (str1.length <= 1) {
  return str1;
 }

  mid_char = str1.substring(1, str1.length - 1);
  return (str1.charAt(str1.length - 1)) + mid_char + str1.charAt(0);
 }
 console.log(first_last('Hello there')); //eello therH

Solution

  • first split the sentence to word and then swap the first and last letter

    const str = "This is a hello world string";
    
    const result = str.split(" ").map(word => {
      const len = word.length;
      if (len > 1) {
        word = word[len-1] +  word.substring(1, len-1) + word[0];
      }
      return word;
    }).join(" ");
    
    console.log(result)

    breaking it into statements for people who find the implementation difficult to comprehend

    const str = "This is a hello world string";
    
    const arr = str.split(" ");
    
    const swapWords = arr.map(word => {
      const len = word.length;
      if (len > 1) {
        word = word[len - 1] + word.substring(1, len - 1) + word[0];
      }
      return word;
    });
    
    const result = swapWords.join(" ");
    
    console.log(result)