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:
xxxxxxxxxx
1
const text = 'This is example text';
2
3
const result = text
4
.split(' ')
5
.map((word) => {
6
if (word.length > 1) {
7
word = word[word.length - 1] + word.substring(1, word.length - 1) + word[0];
8
}
9
return word;
10
})
11
.join(' ');
12
13
console.log(result);
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.
xxxxxxxxxx
1
const swapFirstAndLast = (text) => {
2
return text
3
.split(' ')
4
.map((word) => {
5
if (word.length > 1) {
6
word = word[word.length - 1] + word.substring(1, word.length - 1) + word[0];
7
}
8
return word;
9
})
10
.join(' ');
11
};
12
13
14
// Usage example
15
const text = 'This is example text';
16
17
console.log(swapFirstAndLast(text));
Output:
xxxxxxxxxx
1
shiT si example text