Languages
[Edit]
EN

JavaScript - swap first and last character in every word in string

0 points
Created by:
Savannah
559

In this article, we would like to show you how to swap the first and last character in every word in a string in JavaScript.

Quick solution:

// ONLINE-RUNNER:browser;

const text = 'This is example text';

const result = text
    .split(' ')
    .map((word) => {
        if (word.length > 1) {
            word = word[word.length - 1] + word.substring(1, word.length - 1) + word[0];
        }
        return word;
    })
    .join(' ');

console.log(result);

 

 

Reusable function

In this example, we create a reusable function that splits given text into an array of words, swaps each word's first and last letter, and joins them back into the string.

// ONLINE-RUNNER:browser;

const swapFirstAndLast = (text) => {
    return text
        .split(' ')
        .map((word) => {
            if (word.length > 1) {
                word = word[word.length - 1] + word.substring(1, word.length - 1) + word[0];
            }
            return word;
        })
        .join(' ');
};


// Usage example
const text = 'This is example text';

console.log(swapFirstAndLast(text));

Output:

shiT si example text

References

  1. String.prototype.split() - JavaScript | MDN
  2. Array.prototype.map() - JavaScript | MDN
  3. String.prototype.substring() - JavaScript | MDN
  4. Array.prototype.join() - JavaScript | MDN

Alternative titles

  1. JavaScript - swap first and last character in every word in text
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join