Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

swap - 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
question from:https://stackoverflow.com/questions/65854575/swapping-the-first-and-last-letters-of-every-word-in-a-string-using-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...