EN
JavaScript - swap first and last character in every word in string
0
points
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